自动 XML 数据收集显示在 Google Sheet 中

Automated XML data collection to display in a Google Sheet

我一直在尝试制作一个 Google 脚本,它可以在 Google Sheet 中显示最新的河流水位。 我正在查看 XML 文档,它是 here

这是一份很长的文件,但我想从中提取的只是观察到的河流水位。 目前我有一个 google sheet 设置,河流水位将收集所有数据。我最初通过 XMLhttprequest 让它工作,但发现 google 脚本不支持该功能。所以我一直在尝试使用 UrlFetch service,但还没有太多运气。

我正在处理的代码如下所示:

function Rivers() {
  var url = 'https://water.weather.gov/ahps2/hydrograph_to_xml.php?gage=llrw4&output=xml';

  var xml = UrlFetchApp.fetch(url).getContentText();

  var document = XmlService.parse(xml);

  var txt = "";
  path = "//site/observed/datum/primary"
  var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
  var result = nodes.iterateNext();


  while (result) {
    txt += result.childNodes[0].nodeValue;
    result = nodes.iterateNext();

  }
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var sheet = ss.getSheets()[0];

  var cell = sheet.getRange('B:C');
}

当我尝试 运行 它时,我收到错误 "Cannot find function evaluate" 我确定这与 fetchurl 有关,但似乎无法找到修复它。 任何有关工作的帮助将不胜感激。

Google Apps 脚本在 Google 服务器上运行。因此,您无法访问浏览器中可用的某些 DOM / BOM 功能或 API。这包括用于导航 xml 文档的 XPath。如果要使用 Xpath,则必须编写自己的函数来解析它。这是我找到的示例 https://coderwall.com/p/cq63og/extract-data-from-xpath-via-google-apps-script

XmlService 有自己的方法来遍历 xml 文档,您可以使用这些方法代替 XPath。这就是您获取根元素的所有子节点的方式。

 var url = 'https://water.weather.gov/ahps2/hydrograph_to_xml.php?gage=llrw4&output=xml';

  var xml = UrlFetchApp.fetch(url).getContentText();


  var document = XmlService.parse(xml);
  var root = document.getRootElement();
  var children = root.getChildren();

您收到错误是因为您在字符串变量上调用函数。

  var xml = UrlFetchApp.fetch(url).getContentText();
  var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);

UrlFetchApp.fetch() 的 return 类型是 HttpResponse。调用 HttpResponse 的 getContentText() 方法 returns 一个字符串。此处有更多相关信息 https://developers.google.com/apps-script/reference/url-fetch/http-response.