【发布时间】:2016-07-29 07:53:50
【问题描述】:
为什么System.Xml.XmlDocument 上的 XPath 找不到相邻的文本和 CData 节点?
var raw_xml = @"
<root>
<test>
<![CDATA[This is a CDATA node]]>And this is an adjacent text node
</test>
</root>
";
var doc = new XmlDocument();
doc.LoadXml(raw_xml);
var results = doc.SelectNodes("/root/test/text()");
Console.WriteLine(results.Count); // gives: 1
Console.WriteLine(results[0].Value); // gives: This is a CDATA node
Console.WriteLine(results[0].Name); // gives: #cdata-section
Console.WriteLine(results[0].GetType().FullName); // gives: System.Xml.XmlCDataSection
Console.WriteLine(results[0].NextSibling.Name); // gives: #text
Console.WriteLine(results[0].NextSibling.Value.Trim()); // gives: And this is an adjacent text node
从上面我们可以看出,CDATA 节点将文本节点作为它的下一个兄弟节点,因此您会认为表达式 /root/test/text() 会找到它。
与 XPath 相同的结果:/root/test/node()
【问题讨论】:
-
考虑将问题更改为
Why does XPath over a System.Xml.XmlDocument not find adjacent text and CData nodes?作为整个问题,并且您的答案特定于 .NET 框架中的 DOM 实现以及您的假设“我们可以从上面看到 CDATA 节点具有文本节点是下一个兄弟节点,因此您会认为表达式 /root/test/text()" 在不知道任何 CDATA 节点的 XPath 数据模型中没有基础。 -
@Martin,好点子 - 谢谢。我已经更新了 OP :)
标签: c# xml xpath cdata xpath-1.0