如何:查找前面紧邻的同级 (XPath-LINQ to XML)

更新:November 2007

有时,您需要查找某一节点的前面紧邻同级。 由于与 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");
else
    Console.WriteLine("Results differ");
Console.WriteLine(el1);
Dim root As XElement = _ 
    <Root>
        <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")
Else
    Console.WriteLine("Results differ")
End If
Console.WriteLine(el1)

本示例生成以下输出:

Results are identical
<Child3 />

请参见

概念

针对 XPath 用户的 LINQ to XML