问题
I have a file with the following content (myfile.xml). I have to get all content coming under (including product node) a product with id=1
.
<products>
<product id="1">
<category>q</category>
</product>
<product id="2">
<category>w</category>
</product>
<product id="3">
<category>e</category>
</product>
</products>`
i.e. the result should be :
<product id="1">
<category>q</category>
</product>
How can I do this?
回答1:
var root = XElement.Load("path to the file");
var node = root.Descendants("product").FirstOrDefault(e=>e.Attribute("id").Value == "1");
回答2:
using XPath in Linq
var root = XElement.Load("myfile.xml");
root.XPathSelectElements( "/products/product[@id=1]");
来源:https://stackoverflow.com/questions/10617994/getting-data-from-xml-by-attribute-vlaue