Xdocument save save space inside tags

I use XDocument in LINQ to edit (paste) and save an XML document.

XDocument doc = XDocument.Load("c:\\sample.xml", LoadOptions.PreserveWhitespace); doc.Save("c:\\sample.xml",SaveOptions.DisableFormatting) 

sample.xml before doc.Save:

 <ELEMENT ATTRIB1="attrib1" ATTRIB2="attrib2" > value </ELEMENT> 

sample.xml after doc.Save

 <ELEMENT ATTRIB1="attrib1" ATTRIB2="attrib2"> value </ELEMENT> 

As you can see, after ATTRIB1 and the space after ATTRIB2 there is double space in the source document. But these spaces were removed by linq when I call doc.save.

How to keep spaces inside a tag?

+6
source share
2 answers

I believe that LoadOptions.PreserveWhitespace and SaveOptions.DisableFormatting only instruct XDocument on how to handle spaces in terms of indentation and text node content. It normalizes attributes anyway, etc.

You might want to use overloading where you specify an XmlWriter that is configured as you need, and if you cannot find a configuration that works with XmlTextWriter by default, you can always create your own XmlWriter.

+11
source

These are โ€œminor spacesโ€ and are removed when you read the XML. By the time you call save, there is no information about the interval between attributes. (Note that strictly speaking, even the order of the attributes cannot be known, since it does not matter in XML).

If you want to read / write XML in a way that is not directly supported by the XML standard, you need to provide some custom processing. Depending on the requirements, a custom XmlWriter may be enough (i.e. if you need equally different attributes with two spaces), or you need to assemble the entire stack (readers / writers / nodes) yourself if you want to actually save information from the original XML (treating it as text, not XML).

+1
source

Source: https://habr.com/ru/post/904294/


All Articles