user2154731
user2154731

Reputation: 203

Extract XML tag content in Perl using XML::LibXML

I have the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <basic-dependencies>
          <dep type="nn">
            <governor idx="2">Planted</governor>
            <dependent idx="1">Europeans</dependent>
          </dep>
        </basic-dependencies>
      </sentence>
    </sentences>
  </document>
</root>

I can extract the contents 'Europeans' using the code given below. Is there any way I can extract "nn" from the tag using XML::LibXML?

use strict;
use warnings;
use XML::LibXML qw( );
my $output = $filename.'.xml';
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($output);
for my $dependency_node ($doc->findnodes('//document/sentences/sentence/basic-dependencies'))
{
    for my $dependent_node ($dependency_node->findnodes('dep'))
    {
            my $word = $dependent_node->findvalue('dependent/text()');
            print "$word\n";
    }
}

Upvotes: 2

Views: 469

Answers (1)

choroba
choroba

Reputation: 241858

Yes, just change the assignment to

my $word = $dependent_node->findvalue('@type');

Attributes in XPath start with the @ sign.

Upvotes: 3

Related Questions