On Jun 25, 5:52*pm, JAM <ja_1...@yahoo.comwrote:
Quote:
I'm trying to code some directory structure as my output / input file
using XML. I would like to see formatiing with indentations. mimicking
directory tree structure. Unfortunately the code such as this:
>
using (XmlTextWriter xw = new XmlTextWriter("C:\\Temp\\test.xml",
Encoding.UTF8))
{
* * xw.Formatting = Formatting.Indented;
* * xw.WriteStartDocument();
* * xw.WriteStartElement("FILTER", "");
* * xw.WriteStartElement("DA");
* * xw.WriteString("C:");
* * xw.WriteStartElement("DA");
* * xw.WriteString("Temp");
* * xw.WriteEndElement();
* * xw.WriteEndElement();
* * xw.WriteEndElement();
* * xw.WriteEndDocument();
* * xw.Close();}
>
System.Diagnostics.Process.Start("notepad.exe", "C:\\Temp\\test.xml");
>
Produces only partially indented output:
>
<?xml version="1.0" encoding="utf-8"?>
<FILTER>
* <DA>C:<DA>Temp</DA></DA>
</FILTER>
>
*Where obviously my intent was to get:
>
<?xml version="1.0" encoding="utf-8"?>
<FILTER>
* <DA>
* * C:
* * <DA>
* * * Temp
* * </DA>
* </DA>
</FILTER>
>
(where Temp is a subdirectory of the drive C:)
The problem here is that your second example does not represent the
XML you've outputted - if you read it using XmlReader, you'll notice
that you won't read back plain "C:", but instead it will have some
leading and trailing whitespace. This is due to the nature of
whitespace handling in XML - read the XML specification for more
information. In this case, XmlWriter just did precisely what you asked
it to do - namely, to generate a file which contains string "C:", with
no whitespace at the beginning or at the end. This is actually covered
by MSDN, in documentation for XmlWriterProperties.Indent property:
"The elements are indented as long as the element does not contain
mixed content. Once the WriteString or WriteWhitespace method is
called to write out a mixed element content, the XmlWriter stops
indenting. The indenting resumes once the mixed content element is
closed."
By the way, do not use XmlTextWriter - it's deprecated. Use
XmlWriter.Create instead.