HOW TO:尋找根項目 (XPath-LINQ to XML)

本主題顯示如何利用 XPath 和 LINQ to XML 取得根項目。

XPath 運算式為:

/PurchaseOrders

範例

這個範例會尋找根項目。

此範例使用下列 XML 文件:XML 範例檔:多個採購訂單 (LINQ to XML)

XDocument po = XDocument.Load("PurchaseOrders.xml");

// LINQ to XML query
XElement el1 = po.Root;

// XPath expression
XElement el2 = po.XPathSelectElement("/PurchaseOrders");

if (el1 == el2)
    Console.WriteLine("Results are identical");
else
    Console.WriteLine("Results differ");
Console.WriteLine(el1.Name);
Dim po As XDocument = XDocument.Load("PurchaseOrders.xml")

' LINQ to XML query
Dim el1 As XElement = po.Root

' XPath expression
Dim el2 As XElement = po.XPathSelectElement("/PurchaseOrders")

If el1 Is el2 Then
    Console.WriteLine("Results are identical")
Else
    Console.WriteLine("Results differ")
End If
Console.WriteLine(el1.Name)

這個範例產生下列輸出:

Results are identical
PurchaseOrders

請參閱

概念

適用於 XPath 使用者的 LINQ to XML