I'm still struggling with the XML to Linq syntax.
I have a XML-structure where I'm trying to query the different prices of a product.
This is the 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>
There is a big amount of <product>
in the XML-file so I'm trying to query the price of a specific productname.
Does anybody know how to do this?
You can use the XElement
class. Look at the related post: How to use a LINQ query to get XElement values when XElements have same name .
Do something like:
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();
You could do additional null checking with C# 6 null-propagation operator.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.