-1

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

So this is my example-XML:

<MyXml>
    <SomeNumber>123</SomeNumber>
    <EmptyOne/>
    <NullableElement xsi:nil="true"></NullableElement>
</MyXml>

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);
Streuner
  • 125
  • 1
  • 1
  • 15
  • There's a reason `XML::Simple` is [discouraged](http://stackoverflow.com/questions/33267765/why-is-xmlsimple-discouraged). Stick with `XML::Twig` `XML::LibXML`. – Sobrique May 06 '16 at 22:35

2 Answers2

0

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 => '');

to

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.

Streuner
  • 125
  • 1
  • 1
  • 15
  • 1
    Have you seen the massive antipathy towards `XML::Simple`? I'm surprised you haven't been flooded with answers that tell you to look at [the module's documentation](https://metacpan.org/pod/XML::Simple) which says *"You really don't want to use this module in new code"*. Please try [XML::Twig](https://metacpan.org/pod/XML::Twig) or [XML::LibXML](https://metacpan.org/pod/XML::LibXML) and save yourself some tears – Borodin Apr 25 '16 at 14:32
  • In my typical projects I use XML::LibXML by myself. In this case I just adopted the project from a colleague ;) I was wondering if there are any other solutions to achieve this and as I mentioned in my questions, I'm not forced to use XML::Simple. – Streuner Apr 25 '16 at 14:36
0

In XML::Twig:

use XML::Twig;
my $xmlIn =
  '<MyXml><SomeNumber>123</SomeNumber><EmptyOne/><NullableElement xsi:nil="true"></NullableElement></MyXml>';

print XML::Twig->parse($xmlIn)->get_xpath( '//NullableElement', 0 )->text, "\n";

XML::Simple: Why is XML::Simple "Discouraged"?

It just isn't worth using, as it's a road to brittle code.

Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101