Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

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?

like image 719
bsh152s Avatar asked Oct 12 '09 14:10

bsh152s


2 Answers

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>
like image 52
heijp06 Avatar answered Nov 14 '22 23:11

heijp06


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.

like image 36
Lucero Avatar answered Nov 14 '22 21:11

Lucero