unable to parse xml file using registered namespace - perl

I am using XML::LibXML to parse a XML file. There seems to some problem in using registered namespace while accessing the node elements. I am planning to covert this xml data into CSV file. I am trying to access each and every element here. To start with I tried out extracting attribute values of <country> and <state> tags. Below is the code I have come with . But I am getting error saying XPath error : Undefined namespace prefix.
use strict;
use warnings;
use Data::Dumper;
use XML::LibXML;
my $XML=<<EOF;
<DataSet xmlns="http://www.w3schools.com" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd">
<exec>
<survey_region ver="1.1" type="x789" date="20160312"/>
<survey_loc ver="1.1" type="x789" date="20160312"/>
<note>Population survey</note>
</exec>
<country name="ABC" type="MALE">
<state name="ABC_state1" result="PASS">
<info>
<type>literacy rate comparison</type>
</info>
<comment><![CDATA[
Some random text
contained here
]]></comment>
</state>
</country>
<country name="XYZ" type="MALE">
<state name="XYZ_state2" result="FAIL">
<info>
<type>literacy rate comparison</type>
</info>
<comment><![CDATA[
any random text data
]]></comment>
</state>
</country>
</DataSet>
EOF
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string($XML);
my $xc = XML::LibXML::XPathContext->new($doc);
$xc->registerNs('x','http://www.w3schools.com');
foreach my $camelid ($xc->findnodes('//x:DataSet')) {
my $country_name = $camelid->findvalue('./x:country/#name');
my $country_type = $camelid->findvalue('./x:country/#type');
my $state_name = $camelid->findvalue('./x:state/#name');
my $state_result = $camelid->findvalue('./x:state/#result');
print "state_name ($state_name)\n";
print "state_result ($state_result)\n";
print "country_name ($country_name)\n";
print "country_type ($country_type)\n";
}
Update
if I remove the name space from XML and change my XPath slightly it seems to work. Can someone help me understand the difference.
foreach my $camelid ($xc->findnodes('//DataSet')) {
my $country_name = $camelid->findvalue('./country/#name');
my $country_type = $camelid->findvalue('./country/#type');
my $state_name = $camelid->findvalue('./country/state/#name');
my $state_result = $camelid->findvalue('./country/state/#result');
print "state_name ($state_name)\n";
print "state_result ($state_result)\n";
print "country_name ($country_name)\n";
print "country_type ($country_type)\n";
}

This would be my approach
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $XML=<<EOF;
<DataSet xmlns="http://www.w3schools.com" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd">
<exec>
<survey_region ver="1.1" type="x789" date="20160312"/>
<survey_loc ver="1.1" type="x789" date="20160312"/>
<note>Population survey</note>
</exec>
<country name="ABC" type="MALE">
<state name="ABC_state1" result="PASS">
<info>
<type>literacy rate comparison</type>
</info>
<comment><![CDATA[
Some random text
contained here
]]></comment>
</state>
</country>
<country name="XYZ" type="MALE">
<state name="XYZ_state2" result="FAIL">
<info>
<type>literacy rate comparison</type>
</info>
<comment><![CDATA[
any random text data
]]></comment>
</state>
</country>
</DataSet>
EOF
my $parser = XML::LibXML->new();
my $tree = $parser->parse_string($XML);
my $root = $tree->getDocumentElement;
my #country = $root->getElementsByTagName('country');
foreach my $citem(#country){
my $country_name = $citem->getAttribute('name');
my $country_type = $citem->getAttribute('type');
print "Country Name -- $country_name\nCountry Type -- $country_type\n";
my #state = $citem->getElementsByTagName('state');
foreach my $sitem(#state){
my #info = $sitem->getElementsByTagName('info');
my $state_name = $sitem->getAttribute('name');
my $state_result = $sitem->getAttribute('result');
print "State Name -- $state_name\nState Result -- $state_result\n";
foreach my $i (#info){
my $text = $i->getElementsByTagName('type');
print "Info --- $text\n";
}
}
print "\n";
}
Of course you can manipulate the data anyway you'd like. If you are parsing from a file change parse_string to parse_file.
For the individual elements in the xml use the getElementsByTagName to get the elements within the tags. This should be enough to get you going

There seem to be two small mistakes here.
1. call findvalue for the XPathContext document with the context node as parameter.
2. name is a attribute in country no a node.
Therefor try :
my $country_name = $xc->findvalue('./x:country/#name', $camelid );
Update to the updated question if I remove the name space from XML and change my XPath slightly it seems to work. Can someone help me understand the difference.
To understand what happens here have a look to NOTE ON NAMESPACES AND XPATH
In your case $camelid->findvalue('./x:state/#name'); calls findvalue is called for an node.
But: The recommended way is to use the XML::LibXML::XPathContext module to define an explicit context for XPath evaluation, in which a document independent prefix-to-namespace mapping can be defined. Which I did above.
Conclusion:
Calling find on a node will only work: if the root element had no namespace
(or if you use the same prefix as in the xml doucment if ther is any)

Related

How to parse <rss> tag with XML::LibXML to find xmlns defintions

It seems that there is no consistent way that podcasts define their rss feeds.
Ran into one that is using different schema defs for the RSS.
What's the best way to scan for xmlnamespace in an RSS url, using XML::LibXML
E.g.
One feed might be
<rss
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
Another might be
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom">
I want to include in my script an assessment of all the namespaces being used so that when parsing the rss, the appropriate field names can be tracked.
Not sure what that will look like yet, as I'm not sure this module has the capability to do the <rss> tag attribute atomization that I want.
I'm not sure I understand exactly what kind of output you're looking for, but XML::LibXML is indeed able to list the namespaces:
use warnings;
use strict;
use XML::LibXML;
my $dom = XML::LibXML->load_xml(string => <<'EOT');
<rss
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
</rss>
EOT
for my $ns ($dom->documentElement->getNamespaces) {
print $ns->getLocalName(), " / ", $ns->getData(), "\n";
}
Output:
content / http://purl.org/rss/1.0/modules/content/
wfw / http://wellformedweb.org/CommentAPI/
dc / http://purl.org/dc/elements/1.1/
atom / http://www.w3.org/2005/Atom
sy / http://purl.org/rss/1.0/modules/syndication/
slash / http://purl.org/rss/1.0/modules/slash/
I know that OP has already accepted an answer. But for completeness sake it should be mentioned that the recommended way to make searches on the DOM resilient is to use XML::LibXML::XPathContext:
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my #examples = (
<<EOT
<rss xmlns:atom="http://www.w3.org/2005/Atom">
<atom:test>One Ring to rule them all,</atom:test>
</rss>
EOT
,
<<EOT
<rss xmlns:a="http://www.w3.org/2005/Atom">
<a:test>One Ring to find them,</a:test>
</rss>
EOT
,
<<EOT
<rss xmlns="http://www.w3.org/2005/Atom">
<test>The end...</test>
</rss>
EOT
,
);
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs('atom', 'http://www.w3.org/2005/Atom');
for my $example (#examples) {
my $dom = XML::LibXML->load_xml(string => $example)
or die "XML: $!\n";
for my $node ($xpc->findnodes("//atom:test", $dom)) {
printf("%-10s: %s\n", $node->nodeName, $node->textContent);
}
}
exit 0;
i.e. you assign a local namespace prefix for those namespaces you are interested in.
Output:
$ perl dummy.pl
atom:test : One Ring to rule them all,
a:test : One Ring to find them,
test : The end...

Using Perl and LibXML to obtain sub node values when namespace is used

I have the following XML as an example:
<root xmlns="http://www.plmxml.org/Schemas/PLMXMLSchema" >
<parentNode status="Good">
<A>
<B>
<C id="123" >C Node Value Here</C>
</B>
</A>
</parentNode>
</root>
There are multiple parentNode nodes in my XML file (only one shown here), so I am cycling through parentNode's. Once I have one, I want to obtain attribute values 3 more levels down in the XML. My XML uses a name space and I have registed the name space in my Perl script as "plm". I can obtain the parentNode attribute value just fine using name space in my path. But when I try to navigate down to node "C" and pickup attribute "id", I am getting the following error:
XPath error : Undefined namespace prefix
error : xmlXPathCompiledEval: evaluation failed
I am using the following Perl script.
use XML::LibXML;
use XML::LibXML::XPathContext;
my $filename = "namespaceissue.xml";
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($filename);
my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() );
$xc->registerNs('plm', 'http://www.plmxml.org/Schemas/PLMXMLSchema');
foreach my $node ($xc->findnodes('/plm:root/plm:parentNode')) {
my $status = $node->findvalue('./#status');
print "Status = $status\n";
my $val = $node->findvalue('./plm:A/plm:B/plm:C/#title');
print "Value = $val\n";
}
If I use no namespace on the sub-nodes ./A/B/C, the script continues with no error, but no value is assigned to $val. If I add the plm: prefix I get the namespace error. Does anybody know what I am doing wrong here? Do I have to use findnodes to first find the subnodes and then extract the value with findvalue? I tried that as well and did not have any luck.
$node->findvalue('./plm:A/plm:B/plm:C/#title')
should be
$xc->findvalue('./plm:A/plm:B/plm:C/#id', $node)
Tips:
Those leading ./ are useless.
$node->findvalue('./#status')
$xc->findvalue('./plm:A/plm:B/plm:C/#id', $node)
are the same as
$node->findvalue('#status')
$xc->findvalue('plm:A/plm:B/plm:C/#id', $node)
You can use getAttribute to get an element's attribute, so
$node->findvalue('#status')
can also be accomplished more efficiently using
$node->getAttribute('status')

How to actually modify values of an XML file using XML::LibXML

I have an XML file (information.xml). I have to extract element and attribute values from this XML file and insert those element and attribute values into another XML file (build.xml). I have to change the build.xml file by filling the appropriate element values and tags from information.xml file.
I have to use XML::LibXML to do so. I am able to extract the element and attribute values from information.xml. But, I am unable to open and fill those values in build.xml
Example :
information.xml
<info>
<app version="10.5.10" long_name ="My Application">
<name> MyApp </name>
<owner>larry </owner>
<description> This is my first application</description>
</app>
</info>
build.xml
<build long_name="" version="">
<section type="Appdesciption">
<description> </description>
</section>
<section type="Appdetails">
<app_name> </app_name>
<owner></owner>
</section>
</build>
Now, my task is to extract value of owner from information.xml, open build.xml, search for owner tag in build.xml and put the extracted value there.
The Perl script looks like:
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $file1="/root/shubhra/myapp/information.xml";
my $file2="/root/shubhra/myapp/build.xml";
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($file1);
foreach my $line ($doc->findnodes('//info/app'))
{
my $owner= $line->findnodes('./owner'); # 1st way
print "\n",$owner->to_literal,"\n";
my ($long_name) = $line->findvalue('./#long_name'); # 2nd way
print "\n $long_name \n";
my $version = $line->findnodes('#version');
print "\n",$version->to_literal,"\n";
}
my $parser2 = XML::LibXML->new();
my $doc2 = $parser2->parse_file($file2);
foreach my $line2 ($doc2->findnodes('//build'))
{
my ($owner2)= $line2->findnodes('./section/owner/text()');
my ($version2)=$line2->findvalue('./#version');
print "\n Build.xml already has version : $version2 \n";
print "\n Build.xml already has owner :",$owner2->to_literal;
$owner2->setData("Windows Application 2"); # Not changing build.xml
$line2->setAttribute(q|version|,"60.60.60"); # Not changing build.xml
my $changedversion = $line2->getAttribute(q|version|);
#superficially changed but didn't changed build.xml content
print "\n The changed version is : $changedversion";
}
build.xml looks like :
<build long_name="" version="9.10.10">
<section type="Appdesciption">
<description> </description>
</section>
<section type="Appdetails">
<app_name> </app_name>
<owner>shubhra</owner>
</section>
</build>
my $doc3 = XML::LibXML->load_xml(location => $file2, no_blanks => 1);
my $xpath_expression = '/build/section/owner/text()';
my #nodes = $doc3->findnodes( $xpath_expression );
for my $node (#nodes) {
my $content = $node->toString;
$content = $owner;
$node->setData($content);
}
$doc->toFile($file2 . '.new', 1);
The following fails to find anything (setting $owner2 to undef) since owner has no text:
my ($owner2) = $line2->findnodes('./section/owner/text()');
You want
my ($owner2) = $line2->findnodes('./section/owner');
This entails changing
print "\n Build.xml already has owner :", $owner2->to_literal;
to
print "\n Build.xml already has owner :", $owner2->textContent;
and
$owner2->setData("Windows Application 2");
to
$owner2->removeChildNodes();
$owner2->appendText("Windows Application 2");
You imply you want the following to change build.xml, but it doesn't even mention build.xml:
$line2->setAttribute(q|version|, "60.60.60");
It does modify $doc2, but you'll need to add the following code to modify build.xml too:
$doc2->toFile('build.xml');

Perl using XML Path Context to extract out data

I have the following xml
<?xml version="1.0" encoding="utf-8"?>
<Response>
<Function Name="GetSomethingById">
<something idSome="1" Code="1" Description="TEST01" LEFT="0" RIGHT="750" />
</Function>
</Response>
and I want the attributes of <something> node as a hash. Im trying like below
my $xpc = XML::LibXML::XPathContext->new(
XML::LibXML->new()->parse_string($xml) # $xml is containing the above xml
);
my #nodes = $xpc->findnodes('/Response/Function/something');
Im expecting to have something like $nodes[0]->getAttributes, any help?
my %attributes = map { $_->name => $_->value } $node->attributes();
Your XPATH query seems to be wrong - you are searching for '/WSApiResponse/Function/something' while the root node of your XML is Response and not WSApiResponse
From the docs of XML::LibXML::Node (the kind of stuff that findnodes() is expected to return), you should look for my $attrs = $nodes[0]->attributes() instead of $nodes[0]->getAttributes
I use XML::Simple for this type of thing. So if the XML file is data.xml
use strict;
use XML::Simple();
use Data::Dumper();
my $xml = XML::Simple::XMLin( "data.xml" );
print Data::Dumper::Dumper($xml);
my $href = $xml->{Function}->{something};
print Data::Dumper::Dumper($href);
Note: With XML::Simple the root tag maps to the result hash itself. Thus there is no $xml->{Response}

Dropdown-Menu with optgroup

i am trying to create a dynamic dropdown-menu that receives its entries out of an xml-file at script-startup.
first i tried a static version like this:
Tr(td([popup_menu( -name=>'betreff', -values=>[optgroup(-name=>'Mädels',
-values=>['Susi','Steffi',''], -labels=>{'Susi'=>'Petra','Steffi'=>'Paula'})
,optgroup(-name=>'Jungs', -values=>['moe', 'catch',''])])]));
that worked fine.
The prob starts when i try to put the -values-parameter of popup_menu into a scalar variable.
Should somehow lokk similar to that one:
$popup_values = "[optgroup(-name=>'Mädels', -values=>['Susi','Steffi',''],
-labels=>{'Susi'=>'Petra','Steffi'=>'Paula'}),optgroup(-name=>'Jungs',
-values=>['moe', 'catch',''])]"
or with single quotation marks.
The goal is to build that string by concatenating the syntax-corrected elements of the xml-file. Thats because i do not know a priori how many optgroups or list elements within the optgroups will exist.
Any idea?
Thx in advance
Jochen
So you have an XML file which you use to generate that string? Why not directly generate the data structure necessary for the popup_menu call? It's just an array (you can call optgroup while "analysing" the XML file)
If you really want to use the string-solution then you could use eval to transform the string to the data structure. Though this solution has certain security issues.
Reading From XML-File
Here's an example of how to transform form XML to the optgroup, this of course depends on how your XML-file looks like.
use strict;
use warnings;
use XML::Simple;
use CGI qw/:standard/;
my $xmlString = join('', <DATA>);
my $xmlData = XMLin($xmlString);
my #popup_values;
foreach my $group (keys(%{$xmlData->{group}})) {
my (#values, %labels);
my $options = $xmlData->{group}->{$group}->{opt};
foreach my $option (keys(%{$options})) {
push #values, $option;
if(exists($options->{$option}->{label}) &&
'' ne $options->{$option}->{label}) {
$labels{$option} = $options->{$option}->{label};
}
}
push #popup_values, optgroup(-name => $group,
-labels => \%labels,
-values => \#values
);
}
print popup_menu(-name=>'betreff', -values=> \#popup_values);
__DATA__
<?xml version="1.0" encoding="UTF-8" ?>
<dropdown>
<group name="Mädels">
<opt name="Susi" label="Petra"/>
<opt name="Steffi" label="Paula"/>
<opt name="" />
</group>
<group name="Jungs">
<opt name="moe" />
<opt name="catch" />
<opt name="" />
</group>
</dropdown>