簡體   English   中英

使用節點js解析xml數組值

[英]Parse xml array values with node js

我正在使用Node.js框架在AWS上進行開發。 我正在從以下XML中獲取天氣數據:

<?xml version="1.0"?>
<dwml version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.xsd">
  <head>
    <product srsName="WGS 1984" concise-name="time-series" operational-mode="official">
      <title>NOAA's National Weather Service Forecast Data</title>
      <field>meteorological</field>
      <category>forecast</category>
      <creation-date refresh-frequency="PT1H">2016-08-20T18:44:02Z</creation-date>
    </product>
    <source>
      <more-information>http://www.nws.noaa.gov/forecasts/xml/</more-information>
      <production-center>Meteorological Development Laboratory<sub-center>Product Generation Branch</sub-center></production-center>
      <disclaimer>http://www.nws.noaa.gov/disclaimer.html</disclaimer>
      <credit>http://www.weather.gov/</credit>
      <credit-logo>http://www.weather.gov/images/xml_logo.gif</credit-logo>
      <feedback>http://www.weather.gov/feedback.php</feedback>
    </source>
  </head>
  <data>
    <location>
      <location-key>point1</location-key>
      <point latitude="38.99" longitude="-77.02"/>
    </location>
    <location>
      <location-key>point2</location-key>
      <point latitude="39.70" longitude="-104.80"/>
    </location>
    <location>
      <location-key>point3</location-key>
      <point latitude="47.60" longitude="-122.30"/>
    </location>
    <moreWeatherInformation applicable-location="point1">http://forecast.weather.gov/MapClick.php?textField1=38.99&amp;textField2=-77.02</moreWeatherInformation>
    <moreWeatherInformation applicable-location="point2">http://forecast.weather.gov/MapClick.php?textField1=39.70&amp;textField2=-104.80</moreWeatherInformation>
    <moreWeatherInformation applicable-location="point3">http://forecast.weather.gov/MapClick.php?textField1=47.60&amp;textField2=-122.30</moreWeatherInformation>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-1</layout-key>
      <start-valid-time>2016-08-20T08:00:00-04:00</start-valid-time>
      <end-valid-time>2016-08-20T20:00:00-04:00</end-valid-time>
    </time-layout>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-2</layout-key>
      <start-valid-time>2016-08-20T20:00:00-04:00</start-valid-time>
      <end-valid-time>2016-08-21T09:00:00-04:00</end-valid-time>
    </time-layout>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-3</layout-key>
      <start-valid-time>2016-08-20T08:00:00-06:00</start-valid-time>
      <end-valid-time>2016-08-20T20:00:00-06:00</end-valid-time>
    </time-layout>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-4</layout-key>
      <start-valid-time>2016-08-20T20:00:00-06:00</start-valid-time>
      <end-valid-time>2016-08-21T09:00:00-06:00</end-valid-time>
    </time-layout>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-5</layout-key>
      <start-valid-time>2016-08-20T08:00:00-07:00</start-valid-time>
      <end-valid-time>2016-08-20T20:00:00-07:00</end-valid-time>
    </time-layout>
    <time-layout time-coordinate="local" summarization="none">
      <layout-key>k-p24h-n1-6</layout-key>
      <start-valid-time>2016-08-20T20:00:00-07:00</start-valid-time>
      <end-valid-time>2016-08-21T09:00:00-07:00</end-valid-time>
    </time-layout>
    <parameters applicable-location="point1">
      <temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n1-1">
        <name>Daily Maximum Temperature</name>
        <value>90</value>
      </temperature>
      <temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n1-2">
        <name>Daily Minimum Temperature</name>
        <value>73</value>
      </temperature>
    </parameters>
    <parameters applicable-location="point2">
      <temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n1-3">
        <name>Daily Maximum Temperature</name>
        <value>76</value>
      </temperature>
      <temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n1-4">
        <name>Daily Minimum Temperature</name>
        <value>53</value>
      </temperature>
    </parameters>
    <parameters applicable-location="point3">
      <temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n1-5">
        <name>Daily Maximum Temperature</name>
        <value>90</value>
      </temperature>
      <temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n1-6">
        <name>Daily Minimum Temperature</name>
        <value>61</value>
      </temperature>
    </parameters>
  </data>
</dwml>

我在文件頂部有這個:

/** module used for parsing XML easily. https://www.npmjs.com/package/xml2js*/
var parseString = require('xml2js').parseString;

然后我的主要調用此函數:

function getNoaa(){
    var baseURL = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?listLatLon=";

    // Indianapolis
    var originLat = 39.7683800;
    var originLng = -86.1580400;

    // Chicago
    var destLat = 41.881832;
    var destLng = -87.623177;

    baseURL = baseURL.concat(originLat);
    baseURL = baseURL.concat(",");
    baseURL = baseURL.concat(originLng);
    baseURL = baseURL.concat(",");

    baseURL = baseURL.concat(destLat);
    baseURL = baseURL.concat(",");
    baseURL = baseURL.concat(destLng);

    // TIME
    baseURL = baseURL.concat("&product=time-series&begin=2016-08-19T00:00:00&end=2016-08-20T00:00:00");

    // CHARACTERISTICS REQUESTED
    // http://graphical.weather.gov/xml/docs/elementInputNames.php
    baseURL = baseURL.concat("&Unit=e&maxt=maxt&mint=mint&temp=temp&appt=appt&rh=rh");

    console.log(baseURL);

    request(baseURL, function (error, response, body) 
    {
        if (!error && response.statusCode == 200) 
        {
            //console.log(body);

            // parse the XML
            parseString(body, function (err, result) {
                //console.dir(result);

                console.log(result["dwml"]["data"]["location"][1]["point"].latitude);
            });
        }
    })
}

失敗的部分是這一行:

console.log(result["dwml"]["data"]["location"][1]["point"].latitude);

這是我得到的錯誤代碼:

2016-08-20T18:37:49.654Z    312eb295-6705-11e6-9e3c-ff815be91875    TypeError: Cannot read property '1' of undefined
    at /var/task/index.js:109:51
    at Parser.<anonymous> (/var/task/node_modules/xml2js/lib/xml2js.js:489:18)
    at emitOne (events.js:77:13)
    at Parser.emit (events.js:169:7)
    at Object.onclosetag (/var/task/node_modules/xml2js/lib/xml2js.js:447:26)
    at emit (/var/task/node_modules/sax/lib/sax.js:640:35)
    at emitNode (/var/task/node_modules/sax/lib/sax.js:645:5)
    at closeTag (/var/task/node_modules/sax/lib/sax.js:905:7)
    at Object.write (/var/task/node_modules/sax/lib/sax.js:1449:13)
    at Parser.exports.Parser.Parser.parseString (/var/task/node_modules/xml2js/lib/xml2js.js:508:31)

我基本上想知道我在將第二個(或第一個) location節點放入data父節點內時做錯了什么。 我希望能夠獲得latitudelongitude元素的值。

從xml2js解析的數據與xml不是一一對應的,因為在xml中允許多次具有相同的名稱(鍵)。

第二個位置的正確console.log將是:

console.log(result["dwml"]["data"][0]["location"][1]["point"][0]["$"].latitude);

您也可以跳過按鍵的括號:

console.log(result.dwml.data[0].location[1].point[0].$.latitude);

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM