如何在c#中使用linq循环遍历xml?

时间:2014-01-23 12:14:28

标签: linq

<?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?
我只想在控制台中循环并打印值。
以下字段我想在控制台中显示。

  1. pricebook_id
  2. 货币
  3. 显示名称
  4. 描述
  5. onlineflag
  6. PRODUCT_ID

1 个答案:

答案 0 :(得分:0)

这是一个肮脏的例子,没有空值检查,没有假设的遗漏元素。目的只是为了展示如何循环并获得每个感兴趣的元素,就像你在问题中提出的那样:

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);
        }
    }
}
相关问题