[英]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解析器读取
XElement
的Value
s的文字空格?
I have an XML document, part of which looks like this: 我有一个XML文档,其中一部分如下所示:
<NewLineString> </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 <
printed their character numbers correctly ). 但是,没有为每个值打印任何内容( 注意:XML中的其他转义值,例如
<
正确打印其字符数 )。
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> </NewLineString>
<IndentString xml:space="preserve"> </IndentString>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.