开发者

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&#x9;y&#xD;z&#xA;" />


I did not find a real solution, so I ended up with a quick & dirty :

xml = xml.Replace("\t", "&#x9;").Replace("\r", "&#xA;");

better than nothing...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜