Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument changes tab to space

I have a xml-document that simplified looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Node1 separator="    " />

There is a \t as attribute value.

When executing this code

var path = @"C:\test.xml";
var doc = XDocument.Load(path);
doc.Save(path);

the attribute value changed from tab to space.

<?xml version="1.0" encoding="utf-8"?>
<Node1 separator=" " />

Is there a way to preserve the origin value, because it is required to be a tab?

like image 835
dwonisch Avatar asked Feb 18 '26 19:02

dwonisch


1 Answers

This is "XML whitespace normalization in attributes" portion of XML:Attribute-Value Normalization which is default behavior when handling XML documents.

For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value

You should be able to use XmlTextReader.Normalization property as described here. XmlDocument can load from reader XmlDocument.Load.

var path = @"C:\test.xml";
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(path);
doc.Load(reader);
var s = doc.SelectSingleNode("*/@*").InnerText;
Console.WriteLine("|{0}|, {1}", (int)s[0], s.Length); // prints 9 - ASCII code of tab
doc.Save(path);
like image 136
Alexei Levenkov Avatar answered Feb 20 '26 10:02

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!