简体   繁体   English

从C#LINQ解析XML时,如何保留空白字符

[英]How do I preserve whitespace characters when parsing XML from C# LINQ

What do I need to do in either my C# code or my XML document so that the XDocument parser reads literal whitespace for Value s of XElement s? 我需要在C#代码或XML文档中做什么才能让XDocument解析器读取XElementValue s的文字空格?


Background 背景

I have an XML document, part of which looks like this: 我有一个XML文档,其中一部分如下所示:

  <NewLineString>&#10;&#13;</NewLineString> <IndentString> </IndentString> 

I'm adding the values of each XELement to a data dictionary using a LINQ query; 我正在使用LINQ查询将每个XELement的值添加到数据字典中; the .ForEach part looks like this: .ForEach部分如下所示:

  .ForEach(x => SchemaDictionary.Add( LogicHelper.GetEnumValue(x.Name.ToString()), x.Value)); 

To test to see if the whitespace values were preserved, I'm printing out a line of the character numbers of each value item in the data dictionary. 为了测试是否保留了空白值,我打印出数据字典中每个值项的字符编号行。 In the following code, x represents a KeyValuePair and the Aggregate is simply making a string of the character integer values: 在下面的代码中, x表示KeyValuePair ,而Aggregate只是生成字符整数值的字符串:

 x.Value.ToCharArray() .Aggregate<char,string>("",(word,c) => word + ((int)c).ToString() + " " ) )); 

I expected to see 10 13 for the <NewLineString> value and 32 32 32 32 for the <IndentString> value. 我期望看到10 13对于<NewLineString>值和32 32 32 32对于<IndentString>值。 However, nothing was printed for each value ( note: other escaped values in the XML such as &lt; printed their character numbers correctly ). 但是,没有为每个值打印任何内容( 注意:XML中的其他转义值,例如&lt;正确打印其字符数 )。

What do I need to do in either my C# code or my XML document so that my parser adds the complete whitespace string to the Data Dictionary? 我需要在C#代码或XML文档中做什么才能使我的解析器将完整的空白字符串添加到数据字典中?

尝试使用LoadOptions.PreserveWhitespace加载XDocument

Try loading your document this way. 尝试以这种方式加载文档。

XmlDocument doc = new XmlDocument();
    doc.PreserveWhitespace = true;
    doc.Load("book.xml");

or just modify your input xml to: 或者只是将输入xml修改为:

<NewLineString>&#10;&#13;</NewLineString>
<IndentString xml:space="preserve">    </IndentString>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM