Groups | Blog | Home
all groups > dotnet xml > january 2005 >

dotnet xml : XmlTextWriter Formatting and PreserveWhiteSpace


Riko Eksteen
1/20/2005 11:41:09 AM
Hi

I'm reading an xml file into an XmlDocument, adding some nodes, and writing
it back out. I would like the nodes I add to assume the same level of
indeting as the rest of the document. (I load the document with
PreserveWhiteSpace = true.)

I thought I could do this by using an XmlTextWriter with Formatting set to
Formatting.Indented, but this doesn't work. The Formatting.Indented on the
XmlTextWriter only indents my output when I initially load the document with
PreserveWhiteSpace = false. But that defeats my object, as I get nicely
formatted XML, but without the (nice) extra whitespace I had when I first
loaded the XML file.

Is there any XmlTextWriter class that will indent my XML properly according
to already existing whitespace?

I used the following code:

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
xmldoc.PreserveWhitespace = true;
xmldoc.Load(openFileDialog1.FileName);
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.Indented;
xmldoc.Save(writer);
writer.Close();
richTextBox1.Text = sw.ToString();
}

This only works if I set the PreserveWhiteSpace property to false before I
load the document. Even if I set preserveWhiteSpace to false before I call
the Save method, it doesn't work! Any help please?

Riko

Helena Kupkova, MS
1/24/2005 5:43:31 PM
Hi Riko,

The problem you are running into is that once the XmlTextWriter sees a
whitespace in the element content, it turns off the indentation for that
element and its children. That’s because it makes the element to have a mixed
content and we should not indent it. So nothing gets indented under an
element that has a white space (or text node) child, which happens when you
load with preserveWhitespace = true. With preserveWhitespace = false
everything should get correctly indented..

-Helena Kupkova, Webdata Team, Microsoft


[quoted text, click to view]
AddThis Social Bookmark Button