Skip to main content
 首页 » 编程设计

c#之在 C# 中解析天气预报数据(来自 NDFD)

2024年02月23日17hnrainll

我正在使用 > http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl web 服务通过调用 GmlTimeSeries web 方法获取天气详情。现在我只想从 xml 中读取温度、天气图标链接详细信息。 xml 包含大量数据。谁能给出从 xml 中获取所需数据的想法?

NDFD HOme Page

XML 如下所示:Full XML File is Here

我想从下面的 xml 数据中获取温度:

 <gml:featureMember> 
          <app:Forecast_Gml2Point> 
             <gml:position> 
                <gml:Point srsName="EPSG:4326"> 
                   <gml:coordinates>-87.8859170,41.7450495</gml:coordinates> 
                </gml:Point> 
             </gml:position> 
             <app:validTime>2011-06-07T12:00:00</app:validTime> 
             <app:temperature>77.0</app:temperature> 
          </app:Forecast_Gml2Point> 
       </gml:featureMember> 
 
       <gml:featureMember> 
          <app:Forecast_Gml2Point> 
             <gml:position> 
                <gml:Point srsName="EPSG:4326"> 
                   <gml:coordinates>-87.8859170,41.7450495</gml:coordinates> 
                </gml:Point> 
             </gml:position> 
             <app:validTime>2011-06-07T15:00:00</app:validTime> 
             <app:temperature>90.0</app:temperature> 
          </app:Forecast_Gml2Point> 
       </gml:featureMember> 

还有下面的天气短语:

 <gml:featureMember> 
      <app:Forecast_Gml2Point> 
         <gml:position> 
            <gml:Point srsName="EPSG:4326"> 
               <gml:coordinates>-87.8859170,41.7450495</gml:coordinates> 
            </gml:Point> 
         </gml:position> 
         <app:validTime>2011-06-08T03:00:00</app:validTime> 
         <app:weatherPhrase>Mostly Clear</app:weatherPhrase> 
      </app:Forecast_Gml2Point> 
   </gml:featureMember> 
 
   <gml:featureMember> 
      <app:Forecast_Gml2Point> 
         <gml:position> 
            <gml:Point srsName="EPSG:4326"> 
               <gml:coordinates>-87.8859170,41.7450495</gml:coordinates> 
            </gml:Point> 
         </gml:position> 
         <app:validTime>2011-06-08T06:00:00</app:validTime> 
         <app:weatherPhrase>Mostly Clear</app:weatherPhrase> 
      </app:Forecast_Gml2Point> 
   </gml:featureMember> 

上面是一段xml文件。像这样,我有 7 天天气详细信息的大量数据。我需要从上面的 xml 中读取温度和天气状况。

Full XML File is Here

请您参考如下方法:

我想你会找到你的答案here

编辑: 你需要使用命名空间,例如:

XNamespace app = "http://www.weather.gov/forecasts/xml/OGC_services"; 
var result = from i in doc.Descendants(app+"Forecast_Gml2Point") 
                  select new  
                  { 
                      temperature = i.Element(app + "temperature"),  
                      icon = i.Element(app+"weatherIcon") 
                  }; 

编辑 2: 如果您需要使用其他命名空间获取 Element,这是另一个示例:

XNamespace gml ="http://www.opengis.net/gml" 
i.Element(gml+"coordinates" )