【问题标题】:Parse complicated XML with c# Xml to linq使用 c# Xml 将复杂的 XML 解析为 linq
【发布时间】:2018-06-01 12:55:23
【问题描述】:

我是解析 XML 文档的新手。 我有以下要解析的 XML 文档:http://www.petrol.eu/api/fuel_prices.xml

然后得到价格

目前我正在使用以下代码:

        XDocument xDoc = XDocument.Load("http://www.petrol.eu/api/fuel_prices.xml");
        var list = xDoc.Descendants("country").Where(t => t.Attribute("label").Value=="Slovenia").ToList();

        foreach (var country in list)
        {
            var s95 = country.Elements("pricetype").First(p => p.Attribute("type").Value == "price").Value;
            txtBVnosi.Text = s95;
        }

我知道代码是错误的。我现在有点迷茫,因为我不知道如何正确得出价格,因为它是一个相当复杂的结构化 XML,而我发现的所有其他问题都是针对更简单的 XML 文件的。

【问题讨论】:

  • 使用 xml 模式(生成 xsd)并解析它。或者你可以使用这个[链接]msdn.microsoft.com/en-us/library/bb387098.aspx
  • @sushmitgos 这不能解决 OP 的问题。 XML 不是格式错误或无效,他只是没有找到任何元素。
  • @SebastianHofmann.. 啊对!!

标签: c# xml visual-studio linq


【解决方案1】:

您首先需要查看fuel 元素以检索价格。

要获得每种燃料的所有价格,我建议使用Dictionary

Dictionary<string, string> prices = new Dictionary<string, string>();

foreach (var fuel in country.Elements("fuel"))
{
    prices.Add(
        fuel.Attribute("type").Value,
        fuel.Element("priceType").Elements().First(p => p.Attribute("type").Value == "price").Value);
}

之后,你可以很容易地得到一个具体的价格:

var s95 = prices["95"];

但由于我猜(根据您代码中的变量名称)您想获取燃料类型 95 的价格,因此该查询也可以:

var s95 = country.Elements("fuel")
                 .First(f => f.Attribute("type").Value == "95")
                 .Element("priceType")
                 .Elements()
                 .First(p => p.Attribute("type").Value == "price").Value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多