我有以下XML,我需要通过搜索Model Value和StoreName值来获得价格
<?xml version="1.0" encoding="utf-8"?>
<Results>
<Product>
<Model>X-180</Model>
<Prices>
<Price value="180.0" StoreName="StoreA" />
<Price value="181.0" StoreName="StoreB" />
<Price value="181.0" StoreName="StoreC" />
</Prices>
</Product>
<Product>
<Model>LB621120S</Model>
<Prices>
<Price value="2100.0" StoreName="StoreD" />
<Price value="2120" StoreName="StoreF" />
<Price value="4050" StoreName="StoreG" />
</Prices>
</Product>
</Results>
例如: 如果我运行一个函数来获得Model =“LB621120S”和StoreName =“StoreF”的价格 我应该得到价格:2120
这可以在XmlTextReader中使用吗?
答案 0 :(得分:3)
此XPath将返回您想要的Price
元素:
/Results/Product[Model='LB621120S']/Prices/Price[@StoreName='StoreF']
答案 1 :(得分:1)
使用LINQ:
XDocument doc = XDocument.Parse(xml);
var value =
doc.Descendants("Product")
.First(p => p.Descendants("Model").First().Value == "LB621120S")
.Descendants("Price")
.First(p => p.Attribute("StoreName").Value == "StoreF")
.Attribute("value").Value;
答案 2 :(得分:1)
试试这个:
var reader = new XmlTextReader(<XmlPathFileName>);
var doc = new XmlDocument();
doc.Load(reader);
reader.Close();
var root = doc.DocumentElement;
if (root == null)
return;
var node = root.SelectSingleNode("/Results/Product[Model='LB621120S']/Prices/Price[@StoreName='StoreF']");
答案 3 :(得分:0)
xdoc.Descendants("Product")
.Where(p => (string)p.Element("Model") == model)
.Elements("Price")
.Where(p => (string)p.Attribute("StoreName") == store)
.Select(p => (decimal)p.Attribute("value"))
.FirstOrDefault();