如何使用Google App Script解析给定XML元素中的所有值?

时间:2013-04-15 21:50:23

标签: xml xml-parsing google-apps-script

我正在尝试使用以下形式的xml从NOAA源解析温度数据到Google电子表格中:

..... <parameters applicable-location="point1">
<temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n7-1">
<name>Daily Maximum Temperature</name>
<value>63</value>
<value>72</value>
<value>76</value>
<value>78</value>
<value>74</value>
<value>62</value>
<value>58</value>
</temperature>
<temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n6-2">
<name>Daily Minimum Temperature</name>
<value>52</value>
<value>58</value>
<value>56</value>
<value>60</value>
<value>48</value>
<value>45</value>
</temperature>
</parameters>
</data>
</dwml>

我希望标签中的每个数字都来自最大和最小标题,并且位于电子表格中的单独单元格中。我目前的剧本是:

function Temperatures() { var text = UrlFetchApp.fetch("http://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?whichClient=NDFDgen&lat=38.99&lon=-77.01&listLatLon=&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2004-01-01T00%3A00%3A00&end=2017-04-12T00%3A00%3A00&Unit=e&maxt=maxt&mint=mint&Submit=Submit").getContentText();
  return parse(text);
function parse(text) {
  var doc = Xml.parse(text, true);
  var temps = doc.dwml.data.getElement("parameters").getElement("temperature").getElements("value").getText();
  return temps
}
}

但是,运行此脚本只会将单个读取 - 第一个标记63解析为单元格。如果我更改.getElement(“value”)。getText(); to .getElements(“value”)。getText();我收到以下错误消息:“TypeError:无法在对象中找到函数getText。”

感谢您提供任何建议。

罗恩

2 个答案:

答案 0 :(得分:1)

首先通过调用.getElements(“value”)将元素读入数组,然后遍历每个结果数组和getText。

var doc = Xml.parse(text, true);
var temps = [];  // temps will be an array
temps = doc.dwml.data.getElement("parameters").getElement("temperature").getElements("value");
for (var i=0; i < temps.length; i++)
{
  var value = temps[i].getText();
  // do something with the value..
  Logger.log(value);
}

答案 1 :(得分:1)

这是一篇很老的帖子,但我找不到那么好的答案。这是一对使用新的XmlService很好地工作的脚本,并且是迭代的,以获得任意深度的子项。

&#13;
&#13;
function XMLtoAssocArray(xmlString) {
  var xml = XmlService.parse(xmlString)
  var root = xml.getRootElement()
  return XMLhelper(root)
}


function XMLhelper(Element){
  var children = Element.getChildren()
  var out = {}
  if(children.length>0){
    for (var ii = 0; ii<children.length; ii++){
      var child = children[ii]
      var name = child.getName();
      out[name] = XMLhelper(child)
    }
  } else {
    out = Element.getText()
  }
  return out
}
&#13;
&#13;
&#13;