开发者

How to read value of a node in Perl libXML::Reader

开发者 https://www.devze.com 2023-04-12 02:27 出处:网络
My XML looks like this- <info> <name>NameGoesHere</name> <age>99</age> </info>

My XML looks like this-

<info>
<name>NameGoesHere</name>
<age>99</age>
</info>

Using XML::LibXML::Reader, I would 开发者_StackOverflowlike to print the age.

I read the documentation from here, and I am looking for an example. I am able to use $reader->nextElement('info') and then print innerXML but not able to figure out how do I print only age and not the whole innerxml.


Try localName:

#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML::Reader;

my $reader = XML::LibXML::Reader->new(IO => \*DATA)
    or die "Cannot read from \\*DATA\n";

while ( $reader->read ) {
    print $reader->readInnerXml if $reader->localName eq 'age';
}

$reader->finish;

__DATA__
<info>
<name>NameGoesHere</name>
<age>99</age>
</info>

Mostly from Regex: keep everything in <profession></profession> tags


use strict;
use warnings;
use feature qw( say );

use XML::LibXML::Reader qw(
   XML_READER_TYPE_ELEMENT
   XML_READER_TYPE_END_ELEMENT
   XML_READER_TYPE_TEXT
);

my $reader = XML::LibXML::Reader->new(IO => \*DATA);

my $in_age = 0;
my $age;
while ($reader->read()) {
   if ($reader->nodeType() == XML_READER_TYPE_ELEMENT && $reader->name() eq 'age') {
      $age = '' if !$in_age;
      ++$in_age;
   }
   elsif ($reader->nodeType() == XML_READER_TYPE_END_ELEMENT && $reader->name() eq 'age') {
      --$in_age;
      say $age if !$in_age;
   }
   elsif ($in_age && $reader->nodeType() == XML_READER_TYPE_TEXT) {
      $age .= $reader->value();
   }
}

__DATA__
<info>
<name>NameGoesHere</name>
<age>99</age>
</info>
0

精彩评论

暂无评论...
验证码 换一张
取 消