我有温度传感器可以传输三个蜂箱的温度,并且希望能够解析XML流以提供传感器的最后一个值。
我想:
等。
我在Google Scripts中运行以下脚本,但一直收到错误:
在对象<?xml version =“1.0”encoding =“UTF-8”中找不到函数getContentText?>
这是一个简单的脚本:
function XMLing() {
var response = UrlFetchApp.fetch("https://api.cosm.com/v2/feeds/79697.xml?key=[private key here]");
var doc = Xml.parse(response.getContentText(), true);
var records = doc.getElements("current_value");
var details = records[0].getText();
return details;
}
这是XML:
<eeml xmlns="http://www.eeml.org/xsd/0.5.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="0.5.1" xsi:schemaLocation="http://www.eeml.org/xsd/0.5.1 http://www.eeml.org/xsd/0.5.1/0.5.1.xsd">
<environment updated="2012-10-21T00:44:32.162393Z" created="2012-10-10T21:19:43.373591Z" id="79697" creator="https://cosm.com/users/greennomad">
<private>false</private>
<data id="sensor1tem">
<current_value at="2012-10-21T00:44:32.019058Z">67.00</current_value>
<max_value>618.0</max_value>
<min_value>611.0</min_value>
</data>
<data id="sensor2tem">
<current_value at="2012-10-21T00:44:32.019058Z">60.57</current_value>
<max_value>61.5</max_value>
<min_value>60.41</min_value>
</data>
...
答案 0 :(得分:1)
错误消息非常明显:您的响应对象是实际文本(XML响应),而不是具有getContentText()方法的对象。所以这应该有效:
var doc = Xml.parse(response, true);
答案 1 :(得分:0)
您可以检查哪些方法可用:
if (!response.getContentText) {
var props = [];
for (var p in response) {
props.push(p);
}
var name = typeof response;
if (response.contructor) name = response.contructor.name;
return name + " { " + props.join(", ") + " }";
}
我的猜测是UrlFetchApp.fetch()
要么返回一些错误代码,要么对XML文档有特殊响应。
从错误消息中,UrlFetchApp.fetch()
似乎直接返回XML文档。您可能不需要致电Xml.parse()
:
function XMLing() {
var response = UrlFetchApp.fetch("https://api.cosm.com/v2/feeds/79697.xml?key=[private key here]");
var doc = null;
if (response.getContentText) {
doc = Xml.parse(response.getContentText(), true);
}
else if (response.getElements) {
doc = response;
}
else {
var name = typeof response;
if (response.constructor) name = response.constructor.name;
throw new Exception("Incompatible type: " + name);
}
var records = doc.getElements("current_value");
var details = records[0].getText();
return details;
}