如何在 C# 中读取复杂的 XML
本文关键字:复杂 XML 读取 | 更新日期: 2023-09-27 18:36:46
我有以下XML,我需要通过搜索模型值和存储名称值来获取价格
<?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>
例如:如果我运行一个函数来获取模型="LB621120S"和商店名称="商店F"的价格我应该得到价格:2120
这在 XmlTextReader 中可能吗?
此 XPath 将返回您想要的Price
元素:
/Results/Product[Model='LB621120S']/Prices/Price[@StoreName='StoreF']
试试这个:
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']");
使用
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;
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();