如果您可以将 XML 解析为XML,而不仅仅是为了获取数据而必须刮掉的一堆垃圾,那么您将拥有更多的灵活性。为此,请允许我建议一个混合批处理/JScript 解决方案。
这具有额外的好处,使您能够通过XMLHTTP
请求获取 XML 提要,消除对wget
或类似的依赖。
将以下文件另存为weather.bat
,根据需要修改API代码和邮政编码,试一试。
@if (@a==@b) @end /*
:: batch script portion
@echo off
setlocal
set "apicode=A1111111111"
set "zipcode=55555"
set "url=http://api.wxbug.net/getLiveWeatherRSS.aspx?ACode=%apicode%&zipCode=%zipcode%&UnitType=0&OutputType=1"
for /f "tokens=1*" %%a in ('cscript /nologo /e:jscript "%~f0" "%url%" ^|^| goto :EOF') do (
set "%%a=%%b"
)
echo Temp: %awstemp%
echo High: %awstemphigh%
echo Low: %awstemplow%
echo Rate: %awstemprate%
echo;
:: show all variables beginning with aws and their values
set aws
goto :EOF
:: JScript portion */
function die(txt) {
WSH.StdErr.WriteLine(txt.split(/\r?\n/).join(' '));
WSH.Quit(1);
}
var x=new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET",WSH.Arguments(0),true);
x.setRequestHeader('User-Agent','XMLHTTP/1.0');
x.send('');
var timeout = 60;
for (var i = 20 * timeout; x.readyState != 4 && i >= 0; i--) {
if (!i) die("Timeout error.");
WSH.Sleep(50)
};
if (!x.responseXML.hasChildNodes) die(x.responseText);
// Note: These dom nodes are appropriate for getLiveWeatherRSS.aspx and
// getLiveCompactWeatherRSS.aspx. For parsing other feeds, change the
// root XPath node appropriately.
var dom = x.responseXML, dom = dom.selectSingleNode('//aws:ob') || dom.selectSingleNode('//aws:weather');
var out = [];
for (var i=0; i<dom.childNodes.length; i++) {
if (dom.childNodes[i].hasChildNodes) {
var item = dom.childNodes[i].nodeName.replace(/\W/g, '');
var value = dom.childNodes[i].text;
if (/rate$/.test(item) && value && value > 0) value = '+' + value;
var units = dom.childNodes[i].getAttribute('units') || '';
out.push(item + ' ' + value + units.replace('°','°').replace('"',''));
}
}
WSH.Echo(out.join('\n'));