I have a perl script working fine. Script is taking an xml file as input and returning a JSON format of same and also value of a specific element within XML file.
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use XML::Simple;
use XML::XPath;
my $xmlFileName = "jsonconversion.xml";
my $fileNameElement = "//FileName";
# Create the object of XML Simple
$xmlSimple = new XML::Simple(KeepRoot => 1);
# Load the xml file in object
$dataXML = $xmlSimple->XMLin($xmlFileName);
#Searching value using xpath
my $xp = XML::XPath->new(filename => $xmlFileName);
my $filename = $xp->find($fileNameElement);
my $ElementValue = "";
#Fetching value of 'FileName' in 'fileNameValue' variable
if( length $filename ) {
foreach my $node ($filename->get_nodelist) {
$fileNameValue = $node->string_value;
last;
}
}
# use encode json function to convert xml object in json.
my $jsonString = encode_json($dataXML);
#Printing fileNameValue
print "\n\nFile Name is: ".$fileNameValue;
Due to certain restrictions in company i am not allowed to use XML::Xpath perl module, I can use XML:LibXML. i tried understanding how i can make my current code still work by replacing XML::Xpath with XML:LibXML perl module. I refer perl documentations and old post on stackoverflow as well.
here is one sample solution:
my $dom = XML::LibXML->new->parse_file('data.xml');
for my $node ($dom->findnodes('/category/event/@name')) {
my value = $node->toString;
}
but this code involves change my original code completely.
My question here is how can i make use of XML:LibXML perl module replacing perl module XML:XPath with minimal changes. I don't want to re write the whole code again just for sake of using an existing library.
Sample xml file:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Person SchemaVersion="1.0.8">
<ID>0</ID>
<Home ID="ABC-XYZ" State="Unknown">
<Location>
<SiteName></SiteName>
<Number>62</Number>
<MaxSize>0</MaxSize>
<Comment></Comment>
</Location>
<Laptop>
<FileName>/usr/temp/RPM_020515_.tar.gz</FileName>
</Laptop>
</Home>
</Person>
Let me know if any suggestions.
Thanks
NOTE: I got lot of help from folks in stack overflow for writing current perl module and understanding the functionality.
This gets the first like your code:
use XML::LibXML qw( );
my $dom = XML::LibXML->new->parse_file('data.xml');
my ($file_name_node) = $dom->findnodes('//FileName');
my $file_name = $file_name_node ? $file_name_node->textContent() : '';
Or if there can only be one,
use XML::LibXML qw( );
my $dom = XML::LibXML->new->parse_file('data.xml');
my $file_name = $dom->findvalue('//FileName/text()');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With