Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: get text from node - XML::LibXML

by ikegami (Patriarch)
on Jul 21, 2018 at 16:26 UTC ( [id://1219014]=note: print w/replies, xml ) Need Help??


in reply to get text from node - XML::LibXML

Problem #1: You ask for the foo nodes that are children of the document. There are no such nodes.

$doc->findnodes('foo')
should be
$doc->findnodes('seg/foo')
or
$doc->findnodes('/seg/foo')

Problem #2: You ask for the text children of the foo element, but it doesn't have any. It's not even text you want!

$foo->findnodes('text()')
should be
join('', map { $_->toString() } $foo_node->childNodes)
which can be simplified to
join('', $foo_node->childNodes)

Also,

$foo->findvalue('@mid')

is better written as

$foo->getAttribute('mid')

So, we get

use strict; use warnings qw( all ); use feature qw( say ); use XML::LibXML qw( ); my $xml = <<'__EOS__'; <seg><foo mid="0" mtype="seg"><g id="1">Need to export this text</g></ +foo></seg> __EOS__ my $doc = XML::LibXML->new->parse_string($xml); for my $foo_node ($doc->findnodes('/seg/foo')) { my $mid = $foo_node->getAttribute('mid'); my $inner_xml = join('', $foo_node->childNodes); say "$mid $inner_xml"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1219014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-04-24 05:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found