NOAA 天气数据的 Javascript XML 解析 - 从子节点提取数据时出现问题



我希望得到一些关于我正在编写的Javascript代码的帮助,以从NOAA xml文件中提取天气数据(从这里下载:http://graphical.weather.gov/xml/SOAP_server/ndfdXML.htm)。现在,我刚刚将XML的相关部分粘贴为字符串:

var xmlDoc = $.parseXML("<data>
<weather time-layout="k-p3h-n40-2">
<name>Weather Type, Coverage, and Intensity</name>
<weather-conditions/>
<weather-conditions/>
<weather-conditions/>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="sun" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="rain" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="fog" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
</data>")

我正在尝试使用以下代码提取所有"天气类型"属性:

var count = 0
var test_weather = new Array()
$(xmlDoc).find('weather').each(function(){
  $(this).find('weather-conditions').each(function(){
    $(this).find('value').each(function(){
      test_weather[count] = $(this).attr('weather-type')
      count=count+1
    })
  })
})

但这只能找到第一个天气类型值,我无法弄清楚为什么!任何关于我做错了什么的建议,或者关于如何改进我的代码的建议,将不胜感激!

您的 XML 无效。如果不声明命名空间,则不能使用命名空间。

因此,jQuery不会解析第一个xsi:nil属性之后的任何内容(这就是为什么你只找到第一个天气类型值)。您还缺少结束</weather>标记。

如果声明命名空间,它应该按预期工作。

在这种情况下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

这将转化为:

var xmlDoc = $.parseXML("<dwml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
  <data>
    <!-- ... -->
  </data>
</dwml>");

关于我做错了什么的任何建议,或者关于如何改进我的代码的建议

可以通过删除嵌套的.each()方法来改进代码。您可以简化所有内容并使用 .map() 方法将weather-type属性映射到test_weather数组:

工作示例在这里

var test_weather = $('weather weather-conditions value', xmlDoc).map(function () {
  return $(this).attr('weather-type');
}).get();

带有工作代码的代码片段:

var xmlDoc = $.parseXML("<dwml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<data>
<weather time-layout="k-p3h-n40-2">
<name>Weather Type, Coverage, and Intensity</name>
<weather-conditions/>
<weather-conditions/>
<weather-conditions/>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="sun" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="rain" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
<weather-conditions>
<value coverage="areas" intensity="none" weather-type="fog" qualifier="none">
<visibility xsi:nil="true"/>
</value>
</weather-conditions>
</weather>
</data>
</dwml>");
var test_weather = $('weather weather-conditions value', xmlDoc).map(function() {
  return $(this).attr('weather-type');
}).get();
console.log(test_weather);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

最新更新