How to get values from an XML file matching XPath query in C#

后端 未结 1 1076
南笙
南笙 2021-01-23 19:11

I\'m wondering whether there is a way using C# which enables me to return all the inner values within an XML file matching a given XPath query.

Let\'s suppose that we ha

相关标签:
1条回答
  • 2021-01-23 19:55

    One way to do this is to use System.Xml.XPath.Extensions.XPathEvaluate.

    E.g.

    string xmlFilePath = "exampleWithFruits.xml";
    string xPathQuery = "//fruits/apples//@color";
    
    var doc = XDocument.Load(xmlFilePath);
    IEnumerable att = (IEnumerable)doc.XPathEvaluate(xPathQuery);
    string[] matchingValues = att.Cast<XAttribute>().Select(x => x.Value).ToArray();
    

    Or if you prefer XmlDocument:

    var doc = new XmlDocument();
    doc.Load(xmlFilePath);
    string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();
    
    0 讨论(0)
提交回复
热议问题