Search code examples
pythonpython-3.xperllibxml2

Equivalent of python ElementTree.write() in perl with libxml?


With python I would use the ElementTree.write method:

tree.write("myfile", method="text")

So from this xml:

<all>
<a>ABC<b><s> </s>GHJK</b></a>
<z>1234</z>
</all>

I would get:


ABC GHJK
1234

But I couldn't find something similar in the cpan libxml documentation. Is there something similar for perl's libxml ?


Solution

  • You're looking for the textContent method of XML::LibXML::Node:

    #!/usr/bin/env perl
    use warnings;
    use strict;
    use XML::LibXML;
    
    my $dom = XML::LibXML->load_xml(IO => *DATA);
    my $root = $dom->documentElement;
    print $root->textContent;
    
    __DATA__
    <all>
    <a>ABC<b><s> </s>GHJK</b></a>
    <z>1234</z>
    </all>
    

    prints out

    
    ABC GHJK
    1234