繁体   English   中英

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

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

我需要在C#代码或XML文档中做什么才能让XDocument解析器读取XElementValue s的文字空格?


背景

我有一个XML文档,其中一部分如下所示:

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

我正在使用LINQ查询将每个XELement的值添加到数据字典中; .ForEach部分如下所示:

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

为了测试是否保留了空白值,我打印出数据字典中每个值项的字符编号行。 在下面的代码中, x表示KeyValuePair ,而Aggregate只是生成字符整数值的字符串:

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

我期望看到10 13对于<NewLineString>值和32 32 32 32对于<IndentString>值。 但是,没有为每个值打印任何内容( 注意:XML中的其他转义值,例如&lt;正确打印其字符数 )。

我需要在C#代码或XML文档中做什么才能使我的解析器将完整的空白字符串添加到数据字典中?

尝试使用LoadOptions.PreserveWhitespace加载XDocument

尝试以这种方式加载文档。

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

或者只是将输入xml修改为:

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

暂无
暂无

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

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