簡體   English   中英

使用XML :: LibXML :: XPathContext使用Perl解析XML

[英]Parsing XML with Perl using XML::LibXML::XPathContext

我有一個perl子例程,該例程旨在接收基本的xml文檔並使用xpath表達式從文檔中收集特定信息。 這里是

    sub parseXml {
    my ($rawXml) = @_;
    print "Raw XML resonse:\n" . $rawXml . "\n";

    # Set up the XPath search.
    my $xp = XML::LibXML::XPathContext->new;
    my $node = $xp->getContextNode;
    $xp->setContextNode($node);

    # Extract a list apiece of ids, whos, and whats.
    my @ids = $xp->findnodes('//object/void[@property="id"]/int');
    my @whos = $xp->findnodes('//object/void[@property="who"]/string');
    my @whats = $xp->findnodes('//object/void[@property="what"]/string');

    # Iterate over the arrays to print the data.
    my $it = each_array(@ids, @whos, @whats);
    while (my ($id, $who, $what) = $it->()) {
    print sprintf("%2d: ", $id->string_value) . 
        $who->string_value . " -> '" . 
        $what->string_value . "'\n";
    }
}

問題是,當我運行腳本時,出現錯誤消息:

XPathContext:在...行83上丟失當前節點

我做錯了什么? 我是Perl的新手。

您在任何時候都不會解析輸入XML。 鑒於$rawXml是一個字符串,請確保使用

my $dom = XML::LibXML->load_xml(string => $rawXml);
my $xp = XML::LibXML::XPathContext->new($dom);

我的猜測是第83行是my $node = $xp->getContextNode; ,由於文檔當前為空,因此失敗。 無論如何,您都不需要它,並與以下行一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM