Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: get text from node - XML::LibXML

by tangent (Vicar)
on Jul 21, 2018 at 00:17 UTC ( #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? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2022-05-20 13:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (73 votes). Check out past polls.

    Notices?