Partager via


How to: Find the Root Element (XPath-LINQ to XML)

This topic shows how to get the root element with XPath and LINQ to XML.

The XPath expression is:

/PurchaseOrders

Example

This example finds the root element.

This example uses the following XML document: Sample XML File: Multiple Purchase Orders (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)

This example produces the following output:

Results are identical
PurchaseOrders

See Also

Concepts

LINQ to XML for XPath Users