Reputation: 955
I am using perl for converting an XML file JSON. I was able to write the code for converting the input XML file to Json format.
Here is the sample xml:
<?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>
sample perl code doing json conversion:
#!/usr/bin/perl
use JSON;
use XML::Simple;
# Create the object of XML Simple
my $xmlSimple = new XML::Simple(KeepRoot => 1);
# Load the xml file in object
my $dataXML = $xmlSimple->XMLin("input/path/to/above/XMLFILE");
# use encode json function to convert xml object in json.
my $jsonString = encode_json($dataXML);
# finally print json
print $jsonString;
Output JSON value:
{
"Person": {
"ID": "0",
"SchemaVersion": "1.0.8",
"Home": {
"ID": "ABC-XYZ",
"Laptop": {
"FileName": "/usr/temp/RPM_020515_.tar.gz"
},
"Location": {
"Number": "62",
"MaxSize": "0",
"Comment": { },
"SiteName": { }
},
"State": "Unknown"
}
}
}
Above code is working fine.
My question is and this is where i am actually stuck.
I need to do one more thing along with JSON conversion which is checking if element "FileName" in XML is empty or not. if its not extract its value as well.
So output will be two things:
1. XML To JSON convert ( working fine )
2. Along with point 1. extract the value of nested element in XML
"FileName". I need that for some business logic need in next step.
Can some perl experts help me here and suggest me how i can do that in my current perl code.
Thanks for helping in advance. This is my first perl script so please excuse me if this is a too trivial question to ask.
Tried reading the perl docs but not that helpful.
NOTE: I am trying to use only perl built in libraries not any new third party libraries that is the reason i used XML::Simple. Its production code restriction ( very bad boundation ). I hope something for this exists in XML::Simple or JSON.
Upvotes: 2
Views: 7373
Reputation: 406
You should use XML::LibXML instead of XML::Simple. Then use xpath to query each document. I'd take a look at the code of XML::XML2JSON to see if it can be a good fit for the problem…
Upvotes: 1
Reputation: 6642
As XML::Simple docs note, it 'slurps' the XML into a data structure analogous to the input XML. Thus, to figure out the contents of the XML, just treat it as the hash reference it likely is:
if ($dataXML->{Person}{Home}{ID} eq 'foo') {
# Some action
...
}
Upvotes: 1