dreamer dreamer - 23 days ago 5x
Perl Question

Parsing an special xml file using perl

I am trying parse below xml file and get the values of bBranch,Branch...

<xml-fragment xmlns:con="http://some web link">

<con:string name="bBranch" value="in" export="never" />
<con:string name="Branch" value="in" export="never" />

<con:boolean name="cBranch" value="0" export="never" />

I have tried with XML:LibXML and XML::DOM

Here is a code that i tried:-

use XML::DOM;
my $file ="above.xml";
my $parser = XML::DOM::Parser->new();

my $doc = $parser->parsefile($file);

foreach my $entry ($doc->getElementsByTagName('con:properties')) {
my $parent = $entry->getElementsByTagName('con:string')->item(0)->getFirstChild->getNodeValue;
print $parent;


Can't call method "getNodeValue" on an undefined value at ./test2.pl line 6.

Am I missing anything or going in any wrong direction?

Please help.
thanks in advance!


If I were to change my xml file as follows,

<xml-fragment xmlns:con="http://some web link">
<con:string name="Branch" value="Batman" export="never" />
<con:boolean name="cBranch" value="$Branch" export="never" />

How can I get the value for
such that it will fetch me


The problem is that $entry->getElementsByTagName('con:string') returns an array so you need a second loop inside the one that you have. So you can do something like this:

foreach my $entry ($doc->getElementsByTagName('con:properties')) {
        foreach my $elem ($entry->getElementsByTagName('con:string')) {
                my $name = $elem->getAttribute('name');
                my $value = $elem->getAttribute('value');
                print "$name = $value\n";

Note that extracting information like that from xml documents is really tedious, so you may want to look for a solution that allows you to use xpath to access parts of the document. See also choroba's answer for that.