Come eseguire query LINQ to XML tramite XPath (LINQ to XML)

Questo articolo presenta i metodi di estensione che consentono di eseguire query su un albero XML usando XPath. Per informazioni dettagliate sull'utilizzo di questi metodi di estensione, vedere System.Xml.XPath.Extensions.

Nota

A meno che non esista un motivo molto specifico per eseguire query tramite XPath, ad esempio l'uso intensivo di codice legacy, è preferibile non usare XPath con LINQ to XML. Le query XPath non verranno eseguite bene come le query LINQ to XML.

Esempio

Nell'esempio seguente viene creata un piccolo albero XML e viene usato XPathSelectElements per selezionare un set di elementi.

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

Nell'esempio viene prodotto l'output seguente:

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