Perl (Scripting) - XML::Simple Ignore Attributes

by
Jeremy Canfield |
Updated: March 09 2020
| 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