为什么 XPath over aSystem.Xml.XmlDocument
找不到相邻的文本和 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()