如何使用XML::XPath获取属性?
我有一个简短的 perl (cgi) 程序,可以解析并显示一些天气数据。
我从带有嵌套值的 XML 源获取数据,每个值都有唯一的标签。
现在我得到了一些包含多个条目的数据,由一个唯一的“类型”字段区分,然后每个条目都有一个(不同的)值。
以前的数据:
<weather ver="2.0">
<head>
<locale>en_US</locale>
</head>
<loc id="52557">
</loc>
<cc>
<tmp>16</tmp>
<flik>16</flik>
<t>Mostly Cloudy</t>
<bar>
<r>1022.35</r>
<d>steady</d>
</bar>
<wind>
<s>14</s>
<gust>N/A</gust>
<d>120</d>
<t>ESE</t>
</wind>
<hmid>77</hmid>
</cc>
</weather>
所以我可以这样访问:(相关片段..)
use XML::XPath;
use XML::XPath::Parser;
sub getData($) {
my $url = http://wxdata.weather.com/wxdata/weather/local/52557?cc=*&unit=$unit;
return get($url);
# returned values are XML::XPath::Nodeset (not numbers, or strings!!)
my $xml = getData($zip);
$xp = XML::XPath->new($xml);
sub getVal($) { ## ("tag")
my $tag = shift;
return $xp->findvalue($tag)->value();
sub postData($) {
my $wind = getVal('//cc/wind/s');
if($wind=="calm") { $wind=0; }
my $gust = getVal('//cc/wind/gust');
my $dir = getVal('//cc/wind/d');
my $real = getVal('//cc/tmp');
my $felt = getVal('//cc/flik');
my $pres = getVal('//cc/bar/r');
etc.
print "Wind:: ", $wind, " (", $dir, "), Gust:: ", $gust, "n";
}
现在字段是这样的,注意温度和风速如何具有相同的标签,但通过“类型”数据字段进行区分。:
use XML::XPath;
use XML::XPath::Parser;
sub getData($) {
my $url = http://wxdata.weather.com/wxdata/weather/local/52557?cc=*&unit=$unit;
return get($url);
# returned values are XML::XPath::Nodeset (not numbers, or strings!!)
my $xml = getData($zip);
$xp = XML::XPath->new($xml);
sub getVal($) { ## ("tag")
my $tag = shift;
return $xp->findvalue($tag)->value();
sub postData($) {
my $wind = getVal('//cc/wind/s');
if($wind=="calm") { $wind=0; }
my $gust = getVal('//cc/wind/gust');
my $dir = getVal('//cc/wind/d');
my $real = getVal('//cc/tmp');
my $felt = getVal('//cc/flik');
my $pres = getVal('//cc/bar/r');
etc.
print "Wind:: ", $wind, " (", $dir, "), Gust:: ", $gust, "n";
}
我仍然可以访问任何独特的标签,例如
my $dir = getVal('//parameters/direction/value')
但不知道如何访问具有相同标签但不同“类型”字段的值。
my $gust = getVal('//parameters/wind-speed/gust/value'); ??
my $real = getVal('//parameters/temperature/value'); ??
回答
使用谓词,检查type属性,例如 XPath//parameters/wind-speed[@type='gust']或//parameters/wind-speed[@type="gust"].