我需要帮助使用具有特定where条件的LINQ读取xml元素。
我需要为一个县找到max air_temp 即县名=“布恩”和小时id =“06/03/2009 09:00CDT”
我尝试了类似下面的内容,但没有运气:
Dim custs As IEnumerable = From c In Element.Load("C:\meridian.xml").Elements("county") _
Select c.Elements("hour").Elements("air_temp").Max()
For Each x In custs
Response.Write(custs(0).ToString())
Next
-------------------这是xml文件:
<forecasts>
<issued>06/02/2009 12:00CDT</issued>
- <county name="Adair">
- <hour id="06/02/2009 12:00CDT">
<air_temp>61</air_temp>
<cloud_cover>overcast</cloud_cover>
<dew_point>59</dew_point>
<precip_prob>90</precip_prob>
<precip_rate>0.12</precip_rate>
<precip_type>rain</precip_type>
<snow_rate>0.0</snow_rate>
<wind_direction>NE</wind_direction>
<wind_speed>12</wind_speed>
<dew_point_confidence>-3/+3</dew_point_confidence>
<road_temp>64</road_temp>
<road_frost_prob>0</road_frost_prob>
<road_potential_evap_rate>429</road_potential_evap_rate>
<road_temp_confidence>-3/+2</road_temp_confidence>
<dew_point_confidence>-3/+3</dew_point_confidence>
<bridge_temp>63</bridge_temp>
<bridge_temp_confidence>-4/+2</bridge_temp_confidence>
<bridge_frost>NO</bridge_frost>
</hour>
- <hour id="06/02/2009 13:00CDT">
<air_temp>61</air_temp>
<cloud_cover>overcast</cloud_cover>
<dew_point>60</dew_point>
<precip_prob>70</precip_prob>
<precip_rate>0.01</precip_rate>
<precip_type>rain</precip_type>
<snow_rate>0.0</snow_rate>
<wind_direction>ENE</wind_direction>
<wind_speed>10</wind_speed>
<dew_point_confidence>-3/+3</dew_point_confidence>
<road_temp>65</road_temp>
<road_frost_prob>0</road_frost_prob>
<road_potential_evap_rate>411</road_potential_evap_rate>
<road_temp_confidence>-3/+2</road_temp_confidence>
<dew_point_confidence>-3/+3</dew_point_confidence>
<bridge_temp>64</bridge_temp>
<bridge_temp_confidence>-4/+1</bridge_temp_confidence>
<bridge_frost>NO</bridge_frost>
</hour>
答案 0 :(得分:2)
Dim document = XDocument.Load("meridian.xml")
Dim air_temps = From county In document.Root.Elements("county") _
From hour in county.Elements("hour") _
From air_temp in hour.Elements("air_temp") _
Select CInt(air_temp)
Dim max_air_temp = air_temps.Max()
使用XML文字:
Dim forecasts = XElement.Load("meridian.xml")
Dim air_temps = From air_temp In forecasts.<county>.<hour>.<air_temp> _
Select CInt(air_temp)
Dim max_air_temp = air_temps.Max()
答案 1 :(得分:1)
我假设你需要“country / max temp.date / max temp.value”聚合作为输出。如果是这样,这将解决问题:
Dim meridian = XDocument.Load("meridian.xml")
Dim maxByCounty = _
From county In meridian.<forecasts>.<county> _
Let maxHour = (From hour In county.<hour> _
Order By CType(hour.<air_temp>, Integer) Desescending _
).First _
Select New With { .Name = county.<name>, _
.Hour = maxHour.@id,
.AirTemp = maxHour.<air_temp> }
然后你可以使用这样的结果:
For Each m In maxByCounty
Console.WriteLine(m.Name, m.Hour, m.AirTemp)
Next
答案 2 :(得分:1)
不应该是
From hour In county.Elements("hour") Where hour.Attribute("id")...
而不是
From hour In county.Elements("hour") Where county.Element("hour").Attribute("id")...
此外,您不应将回复发布到其他帖子作为额外答案。