HOW TO:使用 XPath 查詢 LINQ to XML

本主題說明可讓您使用 XPath 查詢 XML 樹狀結構的擴充方法。 如需有關使用這些擴充方法的詳細資訊,請參閱 System.Xml.XPath.Extensions

除非您已經有非常特定的理由要使用 XPath 查詢 (例如,廣泛使用舊版程式碼),否則,不建議搭配 LINQ to XML 使用 XPath。 XPath 查詢將不會與 LINQ to XML 查詢一起執行。

範例

下列範例會建立小型 XML 樹狀結構,並使用 XPathSelectElements 來選取一組項目。

XElement root = new XElement("Root",
    new XElement("Child1", 1),
    new XElement("Child1", 2),
    new XElement("Child1", 3),
    new XElement("Child2", 4),
    new XElement("Child2", 5),
    new XElement("Child2", 6)
);
IEnumerable<XElement> list = root.XPathSelectElements("./Child2");
foreach (XElement el in list)
    Console.WriteLine(el);
Dim root As XElement = _
    <Root>
        <Child1>1</Child1>
        <Child1>2</Child1>
        <Child1>3</Child1>
        <Child2>4</Child2>
        <Child2>5</Child2>
        <Child2>6</Child2>
    </Root>

Dim list As IEnumerable(Of XElement) = root.XPathSelectElements("./Child2")
For Each el As XElement In list
    Console.WriteLine(el)
Next

這個範例產生下列輸出:

<Child2>4</Child2>
<Child2>5</Child2>
<Child2>6</Child2>

請參閱

概念

進階查詢技術 (LINQ to XML)