简体   繁体   English

我需要一些使用Linq解析XML的帮助

[英]I Need Some Help Parsing XML with Linq

I'm new to C# and XML and trying to develop a small weather plugin for MediaPortal. 我是C#和XML的新手,正在尝试为MediaPortal开发一个小型天气插件。 I'm trying to parse some XML using Linq in Visual C# 2010 Express and have hit a roadblock. 我试图在Visual C#2010 Express中使用Linq解析一些XML,但遇到了障碍。

Here is a subset of the XML I am trying to parse: 这是我要解析的XML的子集:

<forecast>
  <period textForecastName="Monday">Monday</period>
  <textSummary>Sunny. Low 15. High 26.</textSummary>
<temperatures>
  <textSummary>Low 15. High 26.</textSummary>
  <temperature unitType="metric" units="C" class="high">26</temperature>
  <temperature unitType="metric" units="C" class="low">15</temperature>
  </temperatures>
</forecast>

Here is my working code so far: 到目前为止,这是我的工作代码:

XDocument loaded = XDocument.Parse(strInputXML);
var forecast = from x in loaded.Descendants("forecast")
select new
{
    textSummary = x.Descendants("textSummary").First().Value,
    Period = x.Descendants("period").First().Value,
    Temperatures = x.Descendants("temperatures"),
    Temperature = x.Descendants("temperature"),
    //code to extract high e.g. High = x.Descendants(...class="high"???),
    //code to extract low  e.g. High = x.Descendants(...class="low"???)
};

My code works up to my placeholder comments, but I can't figure out how to extract the high (26) and the low (15) from the XML using Linq. 我的代码可以处理占位符,但我无法弄清楚如何使用Linq从XML中提取高(26)和低(15)。 I could manually parse it from "Temperature", but I'm hoping I can learn a bit more about XML structures. 我可以从“温度”中手动解析它,但是我希望我可以学到更多有关XML结构的知识。

Thanks for any help. 谢谢你的帮助。 Doug 道格

It looks like you want something like : 它看起来像你想要的东西,如

High = (int)x.Descendants("temperature")
            .Single(e => (string)e.Attribute("class") == "high")

This finds the only temperature descendant (if there are none or multiple, it will throw) having attribute class with value high , and then casts its value to an integer. 这将找到唯一一个具有值为high属性class temperature后代(如果不存在或多个,则将抛出),然后将其值转换为整数。

But it isn't entirely clear. 但这还不是很清楚。

Can a forecast element have multiple temperatures elements? forecast元素可以包含多个 temperatures元素吗? Can a temperatures element have multiple temperature elements that have class == "high" ? 一个temperatures元素可以有多个具有class == "high" temperature元素吗? How do you want to deal with different unitTypes ? 您想如何处理不同的unitTypes

To just get the elements out, you can do something like: 要只显示元素,可以执行以下操作:

Highs = x.Descendants("temperature")
         .Where(e => (string)e.Attribute("class") == "high")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM