<?xml version="1.0" encoding="UTF-8"?>
<pricebooks>
<pricebook>
<header pricebook-id="Indian Rupees">
<currency>INR</currency>
<display-name xml:lang="x-default">Indian Rupees</display-name>
<description xml:lang="x-default">Indian Rupees</description>
<online-flag>true</online-flag>
</header>
<price-tables>
<price-table product-id="0100014">
<amount quantity="1">12000.00</amount>
<amount quantity="3">30000.00</amount>
<price-info>testpriceinfo</price-info>
</price-table>
<price-table product-id="LST">
<amount quantity="1">555.00</amount>
</price-table>
</price-tables>
</pricebook>
</pricebooks>
如何使用linq遍历上述xml?
我只想遍历并在控制台中打印值。
我想在控制台中显示以下字段。
这是一个肮脏的例子,不进行空值检查,不假设缺少任何元素。目的只是为了展示如何遍历并获取感兴趣的每个元素,就像您在问题中所问的那样:
var xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<pricebooks>
<pricebook>
<header pricebook-id=""Indian Rupees"">
<currency>INR</currency>
<display-name xml:lang=""x-default"">Indian Rupees</display-name>
<description xml:lang=""x-default"">Indian Rupees</description>
<online-flag>true</online-flag>
</header>
<price-tables>
<price-table product-id=""0100014"">
<amount quantity=""1"">12000.00</amount>
<amount quantity=""3"">30000.00</amount>
<price-info>testpriceinfo</price-info>
</price-table>
<price-table product-id=""LST"">
<amount quantity=""1"">555.00</amount>
</price-table>
</price-tables>
</pricebook>
</pricebooks>";
var doc = XDocument.Parse(xml);
foreach (var pricebook in doc.Descendants("pricebook"))
{
Console.WriteLine(pricebook.Element("header").Attribute("pricebook-id").Value);
Console.WriteLine(pricebook.Element("header").Element("currency").Value);
Console.WriteLine(pricebook.Element("header").Element("display-name").Value);
Console.WriteLine(pricebook.Element("header").Element("description").Value);
Console.WriteLine(pricebook.Element("header").Element("online-flag").Value);
foreach (var priceTable in pricebook.Descendants("price-table"))
{
Console.WriteLine(priceTable.Attribute("product-id").Value);
foreach (var amount in priceTable.Elements("amount"))
{
Console.WriteLine(amount.Attribute("quantity").Value);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句