如何让XDocument.Load保留换行符

don*_*ngx 4 .net c#

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

    xdoc = XDocument.Load(sr);
}
Run Code Online (Sandbox Code Playgroud)

这是我的XML

<sheet name="sheet1" bounds="160,128,464,288">
    <text name="text1" bounds="160,128,464,288" text="a

    b"/>
</sheet>
Run Code Online (Sandbox Code Playgroud)

XDocument.Load转换

a

b
Run Code Online (Sandbox Code Playgroud)

至

a b
Run Code Online (Sandbox Code Playgroud)

如何保留我的换行符?

Ale*_*kov 5

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

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

以下文章的部分样本:

// Create the XML fragment to be parsed. 
string xmlFrag  = 
@"<item attr1='  test A B C
    1 2 3'/>
  <item attr2='&#01;'/>";                         
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"));
Run Code Online (Sandbox Code Playgroud)