繁体   English   中英

C# xml 到 linq 查询

[英]C# xml to linq query

我仍然在为 XML to Linq 语法苦苦挣扎。

我有一个 XML 结构,我试图在其中查询产品的不同价格。

这是 XML:

  <product>
    <description>productname</description>
    <properties>
      <property>
        <key>RetailPrice</key>
        <value>100.00 $</value>
      </property>
      <property>
        <key>StockPrice</key>
        <value>80.00 $</value>
      </property>
    </properties>
  </product>

XML 文件中有大量<product> ,因此我试图查询特定产品名称的价格。

有人知道怎么做这个吗?

您可以使用XElement类。 查看相关帖子: How to use a LINQ query to get XElement values when XElements have same name

做类似的事情:

string[] prices = xml.Elements("product")
.Where(x => x.Element("description").Value == productName)
.Element("properties")
.Elements("property")
.Where(x => x.Element("key").Value == "RetailPrice")
.Select(x => x.Element("value").Value)
.ToArray();

您可以使用 C# 6 空传播运算符进行额外的空检查。

string[] prices = xml.Elements("product")
.Where(x => x.Element("description")?.Value == productName)
.Element("properties")
.Elements("property")
.Where(x => x.Element("key")?.Value == "RetailPrice")
.Select(x => x.Element("value").Value)
.ToArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM