DEV Community

Xliff
Xliff

Posted on

1

Serializing Basic Types to XML

While I am aware that for serializing data, JSON is the lay of the land. However, in the name of completeness, I realize that XML is not quite dead. Far to the contrary XML is still used, particularly when serializing classes.

We have XML::Class, which covers most use-cases, however I was shocked to realize that the basic Cool type was left in the cold.

To this effect I've knocked together the following. Please share your thoughts, comments, additions and constructive thoughts in the comments section!

Now, to the code

sub xml ($_, :$value) {
    when Hash {
      for .pairs {
        "<key>{ .key }</key>" ~
        "<value>{ xml( .value, :!value ) }</value>"
      }
    }

    when Array {
      "<array>{ .map({ xml($_) }).join }</array>"
    }

    when Str {
      [~](
        $value ?? '<value>' !! '',
        '"$_"',
        $value ?? '</value>' !! ''
      );
    }

    when Numeric {
      [~](
        $value ?? '<value>' !! '',
        '$_',
        $value ?? '</value>' !! ''
      )
    }

    default {
      "<warning>Unhandle-able type { .^name }</warning>"
    }
  }
Enter fullscreen mode Exit fullscreen mode

This is just the first draft. I suspect I can add in a section for XML::Class objects in the very near future.

Also, the code is untested. Please mention all bugs and they will be fixed.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

If you found this post helpful, please leave a ❤️ or a friendly comment below!

Okay