Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: get text from node - XML::LibXML

by tangent (Parson)
on Jul 21, 2018 at 00:17 UTC ( [id://1218972]=note: print w/replies, xml ) Need Help??


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

If I understand correctly you want to extract the text and its enclosing tag if it has one, and just the text if it doesn't. This might help:
use XML::LibXML; my $xml = q| <seg> <foo mid="0" mtype="seg"> <g id="1">Need to export this text</g> </foo> <foo mid="1" mtype="seg"> Need to export this text also </foo> </seg>|; my $doc = XML::LibXML->load_xml(string => $xml); my @foos = $doc->findnodes('//foo'); for my $foo (@foos) { my $mid = $foo->getAttribute('mid'); print "mid: $mid "; my @childnodes = $foo->childNodes(); if (@childnodes) { for my $node (@childnodes) { print $node->toString, "\n"; } } else { print $foo->textContent, "\n"; } }
Output:
mid: 0 <g id="1">Need to export this text</g> mid: 1 Need to export this text also
You may need to trim leading and trailing whitespace if your XML contains it.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2024-04-18 13:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found