DEV Community

Xliff
Xliff

Posted on

1 1 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.

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs