How can I use Perl's XML::LibXML to extract an attribute in a tag?

Anandan picture Anandan · Aug 6, 2009 · Viewed 13.2k times · Source

I have an XML file

<PARENT >
<TAG string1="asdf" string2="asdf" >
</TAG >
</PARENT>

I want to extract the string2 value here.. and also I want to set it to a new value..

How to do that?

Answer

zakovyrya picture zakovyrya · Aug 6, 2009

Use XPath expressions

use strict;                                                                                                                      
use warnings;                                                                                                                    

use XML::LibXML;                                                                                                                 
use Data::Dumper;                                                                                                                

my $doc = XML::LibXML->new->parse_string(q{                                                                                      
<PARENT>                                                                                                                         
    <TAG string1="asdf" string2="asdfd">                                                                                         
    </TAG>                                                                                                                       
</PARENT>                                                                                                                        
});                                                                                                                              

my $xpath = '/PARENT/TAG/@string2';                                                                                              
# getting value of attribute:                                                                                                    
print Dumper $doc->findvalue($xpath);                                                                                            
my ($attr) = $doc->findnodes($xpath);                                                                                            

# setting new value:                                                                                                             
$attr->setValue('dfdsa');                                                                                                        
print Dumper $doc->findvalue($xpath);                                                                                            

# do following if you need to get string representation of your XML structure
print Dumper $doc->toString(1);                             

And read documentation, of course :)