How do I find a XML node by path in Linq-to-XML

前端 未结 2 1916
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 10:37

If I get the path to a specific node as a string can I somehow easily find said node by using Linq/Method of the XElement ( or XDocument ).

There are so many differe

相关标签:
2条回答
  • 2021-01-12 11:23

    Try using the XPathSelectElement extension method of XElement. You can pass the method an XPath expression to evaluate. For example:

    XElement myElement = rootElement.XPathSelectElement("//Book[@ISBN='22542']");
    

    Edit:

    In reply to your edit, check your XPath expression. If your document only contains that small snippet then /Product/Name will work as the leading slash performs a search from the root of the document:

    XElement element = document.XPathSelectElement("/Product/Name");
    

    If there are other products and <Product> is not the root node you'll need to modify the XPath you're using.

    0 讨论(0)
  • 2021-01-12 11:24

    You can also use XPathEvaluate

    XDocument document = XDocument.Load("temp.xml");
    var found = document.XPathEvaluate("/documents/items/item") as IEnumerable<object>;
    foreach (var obj in found)
    {
        Console.Out.WriteLine(obj);    
    }
    

    Given the following xml:

    <?xml version="1.0" encoding="utf-8" ?>
    <documents>
      <items>
        <item name="Jamie"></item>
        <item name="John"></item>
      </items>
    </documents>
    

    This should print the contents from the items node.

    0 讨论(0)
提交回复
热议问题