2

このXMLを処理するためにXML::Twigを使用しています:

<?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 に答える