2

我正在使用 XML::Twig 来处理这个 XML:

<?xml version="1.0" encoding="UTF-8"?>
<termEntry>
    <langSet lang="en">
        <ntig>
            <termGrp>
                <term>trail</term>
                <termNote type="partOfSpeech">noun</termNote>
            </termGrp>
            <descrip type="context">Like in a forest</descrip>
        </ntig>
    </langSet>
</termEntry>

我正在使用以下代码来处理它:

use strict;
use XML::Twig;

my $twig_handlers = {
    termEntry => sub { for my $node($_[1]->findnodes('.//descrip|.//termNote')){print $node->text;}},
};

my $twig= new XML::Twig(
                                TwigRoots           => { termEntry => 1},
                                TwigHandlers        => $twig_handlers,
);

$twig->parsefile('C:\Users\me\file.xml');

代码失败:

error in xpath expression .//descrip|.//termNote around descrip|.//termNote at 
C:\Users\nate\Desktop\test.pl line 6

我一直在尝试不同的东西,任何时候我都使用'|' xpath 中的字符会破坏程序。它在http://www.xpathtester.com上工作得很好(以为我用 '//' 替换了 '.')。有想法该怎么解决这个吗?

4

2 回答 2

7

有不止一种方法可以做到:

use strict;
use warnings;
use XML::Twig;

sub process {
  my ( $twig, $elt ) = @_;
  print $_->text, "\n" for ( $elt->findnodes( './/descrip' ),
                             $elt->findnodes( './/termNote' ) );
}

my $xml = XML::Twig->new( twig_roots => { termEntry => \&process } );

$xml->parse( <<XML );
<?xml version="1.0" encoding="UTF-8"?>
<termEntry>
    <langSet lang="en">
        <ntig>
            <termGrp>
                <term>trail</term>
                <termNote type="partOfSpeech">noun</termNote>
            </termGrp>
            <descrip type="context">Like in a forest</descrip>
        </ntig>
    </langSet>
</termEntry>
XML

输出

Like a forest
noun
于 2011-11-19T22:52:57.280 回答
2

文档中:

“XPath 表达式仅限于使用子轴和后代轴(实际上您不能指定轴),并且谓词不能嵌套。您可以使用字符串或 string() 函数(twig_roots 触发器除外)”

您的 XPath 是正确的。您可能想尝试:XML::Twig::Xpath 然后您将获得完整的 Xpath 功能 :)

于 2011-11-19T22:45:33.183 回答