bsh152s
bsh152s

Reputation: 3218

How do I edit XML in C# without changing format/spacing?

I need an application that goes through an xml file, changes some attribute values and adds other attributes. I know I can do this with XmlDocument and XmlWriter. However, I don't want to change the spacing of the document. Is there any way to do this? Or, will I have to parse the file myself?

Upvotes: 6

Views: 2864

Answers (2)

heijp06
heijp06

Reputation: 11788

XmlDocument has a property PreserveWhitespace. If you set this to true insignificant whitespace will be preserved.

See MSDN

EDIT

If I execute the following code, whitespace including line breaks is preserved. (It's true that a space is inserted between <b and />)

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(
    @"<a>
       <b/>
    </a>");
Console.WriteLine(doc.InnerXml);

The output is:

<a>
   <b />
</a>

Upvotes: 8

Lucero
Lucero

Reputation: 60190

Insignificant whitespace will typically be thrown away or reformatted. So unless the XML file uses the xml:space="preserve" attribute on the nodes which shall preserve their exact whitespace, changing whitespace is OK per XML specifications.

Upvotes: 1

Related Questions