retaining leading whitespace in text of an xml node

  • Thread starter Thread starter Steve Richter
  • Start date Start date
S

Steve Richter

when I run the following code the leading spaces of the "data" node
are removed. How do I retain whitespace?

private void CreateBasicXmlDocument()
{
XmlWriterSettings writeSettings = new XmlWriterSettings();
writeSettings.Indent = true;


XmlWriter writer = XmlWriter.Create( filePath, writeSettings );


writer.WriteStartElement("data");
writer.WriteWhitespace(" ");
writer.WriteValue(" data with leading space");
writer.WriteEndElement();
writer.Close();
}
 
Steve,

I think you need to set the XmlSpace attribute of the XmlWriter to
XmlSpace.Preserve.

--BJ
 
Steve,

I think you need to set the XmlSpace attribute of the XmlWriter to
XmlSpace.Preserve.

I tried that. the XmlSpace attribute is read only. very confusing!

-Steve
 
Hi Steve,

The white spaces you add are there. Your code appends a single space character in front of the value.

If you are missing the indentation, bear in mind that WriteWhiteSpace isonly used when manually formatting the xml, which means effectively overriding the indentation. Furthermore, indentation won't happen on the innermost node, and since you only have a single node it won't be broken on two lines. The code below is probably more what you seek.

writer.WriteStartElement("data");
writer.WriteStartElement("innerdata");
writer.WriteValue(" data with leading space");
writer.WriteEndElement();
writer.WriteEndElement();
 
Hi Steve,

The white spaces you add are there. Your code appends a single space character in front
of the value.

your right! <smacks head> I was displaying the xml document thru
Windows Explorer -> Internet Explorer. Whatever font it was in really
shrunk down the whitespace.

thanks,

-Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top