【问题标题】:How can I extract the desired nodes from this XML file using Perl and XPath?如何使用 Perl 和 XPath 从这个 XML 文件中提取所需的节点?
【发布时间】:2010-05-20 00:00:39
【问题描述】:

在执行 XPath 表达式以从 XML DB 文件中提取与死亡率相关的所有年份和值元素后,我想从节点列表中获取每个节点并找到年份节点,打印出来,找到值节点,然后单独打印。问题是输出没有显示任何内容。

XML 内容如下所示:

<dataset type="country" name="Afghanistan" total="222">
...
        <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="SP.DYN.CDRT.IN">Death rate, crude (per 1,000 people)</indicator>
             <year>2006</year>
             <value>20.3410000</value>
           </data>
           <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="SP.DYN.CDRT.IN">Death rate, crude (per 1,000 people)</indicator>
             <year>2007</year>
             <value>19.9480000</value>
           </data>
           <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="SP.DYN.CDRT.IN">Death rate, crude (per 1,000 people)</indicator>
             <year>2008</year>
             <value>19.5720000</value>
           </data>
           <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="IC.EXP.DOCS">Documents to export (number)</indicator>
             <year>2005</year>
             <value>7.0000000</value>
           </data>
           <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="IC.EXP.DOCS">Documents to export (number)</indicator>
             <year>2006</year>
             <value>12.0000000</value>
           </data>
           <data>
             <country id="AFG">Afghanistan</country>
             <indicator id="IC.EXP.DOCS">Documents to export (number)</indicator>
             <year>2007</year>
             <value>12.0000000</value>
           </data>
...
</dataset>

Perl 代码如下所示:

#Use XML Xlib parser to find elements related to death rate

my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($XML_DB);
my $root = XML::LibXML::XPathContext->new($tree->documentElement());
#print $nodeSet->to_literal(); 

foreach my $node ($root->findnodes("/*/data/indicator[\@id = 'SP.DYN.CDRT.IN']/following-sibling::*")) {
    #print $node->textContent() . "\n";
    #print $node->nodeName . "\n";
    print $node->find("year") . "\n";
}
exit;

【问题讨论】:

    标签: perl xpath libxml2


    【解决方案1】:

    find("year") 中的表达式 year 并没有像您想象的那样工作,因为您的复杂选择器不会在 data 节点处结束。使用Xacobeo 调试XPath 表达式。这有效:

    foreach my $node ($root->findnodes(q{/*/data/indicator[@id = 'SP.DYN.CDRT.IN']/following-sibling::*})) {
        say $_->toString for $node->childNodes;
    }
    

    输出:

    2006
    20.3410000
    2007
    19.9480000
    2008
    19.5720000
    

    【讨论】:

    • WTF,Xacobeo 是一个 GUI 应用程序 - 只需安装并运行它。此外,您应该接受答案,请参阅stackoverflow.com/…
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多