如何让XDocument.Load保留换行符

using (System.IO.StreamReader sr = new System.IO.StreamReader(path, System.Text.Encoding.GetEncoding("Windows-1252"), true)) { xdoc = XDocument.Load(sr); } 

这是我的XML

    

XDocument.Load转换

 a b 

 ab 

如何保留我的换行符?

默认情况下,属性中的空格被规范化以转换为空格。 在元素中使用新行而不是属性更安全。

如果它不受您的控制 – 将XmlTextReader.Normalization设置为false应该可以防止默认行为。

以下文章的部分样本:

 // Create the XML fragment to be parsed. string xmlFrag = @" "; XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context); // Show attribute value normalization. reader.Read(); reader.Normalization = false; Console.WriteLine("Attribute value:{0}", reader.GetAttribute("attr1")); reader.Normalization = true; Console.WriteLine("Attribute value:{0}", reader.GetAttribute("attr1"));