本文展示了如何使用
XPathEvaluate
来查找紧接在节点之前的同级节点,以及如何使用 LINQ to XML 查询来执行相同操作。 由于与 LINQ to XML 相比,XPath 中前面紧邻轴的位置谓词的语义同,因此这是一个更值得关注的比较。
示例:查找倒数第二个元素
在本示例中,LINQ to XML 查询使用
Last
运算符查找由
ElementsBeforeSelf
返回的集合中的最后一个节点。 相比之下,XPath 表达式使用值为 1 的谓词来查找前面紧邻的元素。
XElement root = XElement.Parse(
@"<Root>
<Child1/>
<Child2/>
<Child3/>
<Child4/>
</Root>");
XElement child4 = root.Element("Child4");
// LINQ to XML query
XElement el1 =
child4
.ElementsBeforeSelf()
.Last();
// XPath expression
XElement el2 =
((IEnumerable)child4
.XPathEvaluate("preceding-sibling::*[1]"))
.Cast<XElement>()
.First();
if (el1 == el2)
Console.WriteLine("Results are identical");
Console.WriteLine("Results differ");
Console.WriteLine(el1);
Dim root As XElement = _
<Child1/>
<Child2/>
<Child3/>
<Child4/>
</Root>
Dim child4 As XElement = root.Element("Child4")
' LINQ to XML query
Dim el1 As XElement = child4.ElementsBeforeSelf().Last()
' XPath expression
Dim el2 As XElement = _
DirectCast(child4.XPathEvaluate("preceding-sibling::*[1]"), _
IEnumerable).Cast(Of XElement)().First()
If el1 Is el2 Then
Console.WriteLine("Results are identical")
Console.WriteLine("Results differ")
End If
Console.WriteLine(el1)
该示例产生下面的输出:
Results are identical
<Child3 />
针对 XPath 用户的 LINQ to XML (Visal Basic)