Printing keys using XML::Simple in Perl

Home > Search
  by

Let's say you have an extremly simple XML file named cartoon.xml that contains the following markup.

<acme>
  <name>Bugs Bunny</name>
</acme>

 

In this example, "name" is the key and "Bugs Bunny" is the value.

 

The following script will allow you to parse the values from the cartoon.xml file.

#!/usr/bin/perl
use XML::Simple;
$cartoon = XMLin("cartoon.xml");

 

You can print the keys . For example, the following markup will print "name" to the console.

print $_ for keys %$cartoon;

 

XML files can contains numerous "levels". Take for example the following XML.

<acme>
  <one>
    <two>
      <three>
        <name>Bugs Bunny</name>
      </three>
    </two>
  </one>
</acme>

 

In this scenario, to print "Bugs Bunny", you would need to include each "level" in your print statement.

print $_ for keys %{$cartoon->{'one'}->{'two'}->{'three'}};


Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments