Reputation: 31
I am trying to extract the value of two particular attributes from an XML file, whose structure is below;
<environment>
<applications>
<application1>
<app-config>
<server host="boxA" port="1234"/>
</app-config>
</applicaitons>
</environment>
I want to be able to read the value of the attribute "host" and "port".
I've tried with the foillowing piece of code but this doesn't work for me.
#!/usr/local/bin/perl -w
use XML::XPath;
my $file = "configuration.xml";
my $xp = XML::XPath->new(filename => $file);
my $hname = $xp->find('/environment/applications/application1/app-config/server/@host');
my $pnumber = $xp->find('/environment/applications/application1/app-config/server/@port');
print $hname;
But this does not return any output whatsoever when I run this command.
Thanks in advance
Upvotes: 3
Views: 5120
Reputation: 13424
Use XML:Simple. Its, well, simple.
Trying the following code:
use strict;
use warnings;
use XML::Simple;
my $xml = XMLin( <<XML );
<environment>
<applications>
<application1>
<app-config>
<server host="boxA" port="1234"/>
</app-config>
</applicaitons>
</environment>
XML
print $xml->{"applications"}{"app-config"}{"server"}{"host"} . "\n";
print $xml->{"applications"}{"app-config"}{"server"}{"port"} . "\n";
on your XML snippet, you'll get back an error such as:
mismatched tag at line 7, column 9, byte 159 at C:/Perl64/lib/XML/Parser.pm line 187
since its telling me there's a mismatched tag, I start examining the XML until I work out the malformed issues so I work on the XML errors until I come up with:
use strict;
use warnings;
use XML::Simple;
my $xml = XMLin( <<XML );
<environment>
<applications>
<app-config>
<server host="boxA" port="1234"/>
</app-config>
</applications>
</environment>
XML
print $xml->{"applications"}{"app-config"}{"server"}{"host"} . "\n";
print $xml->{"applications"}{"app-config"}{"server"}{"port"} . "\n";
And now the program yields the expected:
boxA
1234
As you can see, it helped me quickly discover the source of the error and with no extra configuration XML::Simple made a very natural mapping to the perl hashes that we all love so well :-) ... simple.
Upvotes: 0
Reputation: 103
</applicaitons>
should be spelled as </applications>
Replace that in your XML document.
The source is fine.
Upvotes: 2
Reputation: 15813
Always, always start your perl scripts with;
use strict;
And while debugging, also do this;
use warnings;
That will show you that your XML is malformed to start with.
Fix your XML and it will work!
Upvotes: 4
Reputation: 37029
Your XML is invalid! Fix it and it works fine.
$ perl test.pl
boxA
Upvotes: 4