【问题标题】:How to get values from an XML file matching XPath query in C#如何从 C# 中匹配 XPath 查询的 XML 文件中获取值
【发布时间】:2012-10-18 09:38:38
【问题描述】:

我想知道是否有一种方法使用 C# 使我能够返回与给定 XPath 查询匹配的 XML 文件中的所有内部值。

假设我们有以下名为 exampleWithFruits.xml 的 XML 文件:

<fruits>
   <bananas>
      <banana id="1" color="yellow" price="0.5" />
      <banana id="2" color="yellow" price="0.4" />
      <banana id="3" color="yellow" price="0.6" />
   </bananas>
   <apples>
      <apple id="1" color="red" price="0.5" />
      <apple id="2" color="red" price="0.4" />
      <apple id="3" color="green" price="0.6" />
      <apple id="4" color="yellow" price="0.4" />
   </apples>
   <oranges>
      <orange id="1" color="orange" price="0.5" />
      <orange id="2" color="orange" price="0.5" />
   </oranges>
</fruits>

如下所示:

string xmlFilePath = "exampleWithFruits.xml";
string xPathQuery = "//fruits/apples//@color"
string[] matchingValues = interestingFunction(xmlFilePath, xPathQuery);
//for instance we would get something like : matchingValues = {red, red, green, yellow}

总结一下,我想知道如何创建interestingFunction

这样的函数

谢谢

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    一种方法是使用System.Xml.XPath.Extensions.XPathEvaluate

    例如

    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();
    

    或者,如果您更喜欢 XmlDocument:

    var doc = new XmlDocument();
    doc.Load(xmlFilePath);
    string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();
    

    【讨论】:

    • 在哪里可以找到 System.Xml.XPath.Extensions.XPathEvaluate?
    • @Pamplemousse 添加对程序集 System.Xml.Linq.dll 的引用
    • 在添加 System.Xml.Linq.dll 程序集引用后,我可以添加 System.Xml.XPath.Extensions 但不能添加 System.Xml.XPath.Extensions.XPathEvaluate。
    • 好的!我在MSDN reference 上找到了它。很简单:using System.Xml.XPath;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多