Bootstrap FreeKB - Perl (Scripting) - XML::Simple Ignore Attributes
Perl (Scripting) - XML::Simple Ignore Attributes

Updated:   |  Perl (Scripting) articles

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";
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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