How to preserve whitespaces in attributes values when using XDocument?
I proce开发者_如何学JAVAss xml which contains tabs ("\t") and line breaks ("\n") in its attributes values. When I parse it using XDocument.Parse(), the tabs and line breaks are converted to spaces, even with the LoadOptions.PreserveWhitespace parameter.
How can I get a XDocument with original attributes values?
You could use a simple XmlTextReader to parse the xml-string. It will preserve all whitespace within attribute values:
string textToParse = "<e a=\"x\ty\rz\n\" />" ;
using (var sr = new StringReader(textToParse)) {
using (var xr = new XmlTextReader(sr)) {
var xd = XDocument.Load(xr);
System.Console.WriteLine(xd.ToString());
}
}
will output
<e a="x	y
z
" />
I did not find a real solution, so I ended up with a quick & dirty :
xml = xml.Replace("\t", "	").Replace("\r", "
");
better than nothing...
精彩评论