Streuner Streuner - 2 years ago 145
Perl Question

Perl XML::Simple: SuppressEmpty for xsi:nil-Elements without content?

I'm struggling with XML::Simple in Perl and nullable Elements.

So this is my example-XML:

<NullableElement xsi:nil="true"></NullableElement>

If I read this with XMLin and SuppressEmpty => 1 I'll get an empty string for the EmptyOne, but a Hash with xsi:nil="true" for the NullableElement. My questions is, how can I tell the XMLin to ignore the xsi:nil-Content and just give me an empty string or undef? Is this even possible with XML::Simple or should I switch to Lib::XML?

Here some code to see the result:

use XML::Simple;
use Data::Dumper;

my $xmlIn = '<MyXml><SomeNumber>123</SomeNumber><EmptyOne/><NullableElement xsi:nil="true"></NullableElement></MyXml>';
my $xmlHash = XMLin($xmlIn, SuppressEmpty => '');

print Dumper($xmlHash);

Answer Source

Well I found a solution for my problem by myself, but this only works for my specific case, because I don't have any attributes I need. If so, you can change the line

my $xmlHash = XMLin($xmlIn, SuppressEmpty => '');


my $xmlHash = XMLin($xmlIn, NoAttr => 1, SuppressEmpty => '');

This will cut off all the attributes and return an empty string like a regular empty Element.

As mentioned before, this will only work if you don't need any attributes from the xml. If you do need them, this won't work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download