Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: XML::LibXML - How to extract an element including the elements within?

by poj (Abbot)
on May 09, 2019 at 20:29 UTC ( [id://1233536]=note: print w/replies, xml ) Need Help??


in reply to XML::LibXML - How to extract an element including the elements within?

Try joining the child nodes

my ($node) = $dom->findnodes('/doc/text'); my $text = join '', $node->childNodes(); print "$text\n";
poj
  • Comment on Re: XML::LibXML - How to extract an element including the elements within?
  • Download Code

Replies are listed 'Best First'.
Re^2: XML::LibXML - How to extract an element including the elements within?
by TravelAddict (Acolyte) on May 10, 2019 at 19:30 UTC

    Thanks poj,

    This works great for me, and I also realized that I can differentiate the type of node that I get (plain text vs. element):

    my ($node) = $dom->findnodes('/doc/text'); my @children = $node->childNodes; foreach my $child (@children) { my $type = ref($child); # $type contains the type of the node, ex: "XML::LibXML::Element" }

    From there, I can have a plain text string (no tags) and a separate list of all the elements embedded.

    Have a great day!

    TA

      my $type = ref($child);

      This is a very brittle way of doing it - it's possible that XML::LibXML::Element could be subclassed, and this check would fail, which is why I would recommend against it. It's possible to do $child->isa('XML::LibXML::Element'), but XML::LibXML provides an API to check the node type: $child->nodeType == XML_ELEMENT_NODE (admittedly not a very Perlish way of doing it, but it's based on the libxml2 API).

        Hi!

        Thanks again for helping me writing a more robust script! Very good advises, very good learning... :-)

        Have a great one!

        TA

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-16 23:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found