FreeKB - XML Simple in Perl - Ignore Attributes
XML Simple in Perl - Ignore Attributes

Home > Search


Let's consider this XML file that contains an attribute. In this example, the attribute is role="Main Character".

<acme>
  <character role="Main Character">
    <name>Bugs Bunny</name>
  </character>
</acme>

 

The following script will probably not produce the expected outcome. This script will print both "role" and "Bugs Bunny".

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

my $xml = XMLin("cartoon.xml");

foreach ( keys %{$xml->{character}} ) {
  print "$_\n";
}

 

This occurs because by default, XML::Simple looks at both the first attribute of the key and the value of the keys below the current key. To resolve this, NoAttr => 1 can be used. This will result in only "Bugs Bunny" being printed.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

my $xml = XMLin("cartoon.xml", NoAttr => 1);

foreach ( keys %{$xml->{character}} ) {
  print "$_\n";
}

 



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 d5011 in the box below so that we can be sure you are a human.




Comments