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

前端 未结 2 1918
佛祖请我去吃肉
佛祖请我去吃肉 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 is not the root node you'll need to modify the XPath you're using.

提交回复
热议问题