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.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Jetbrains Survey

Calling all developers!

Participate in the Developer Ecosystem Survey 2025 and get the chance to win a MacBook Pro, an iPhone 16, or other exciting prizes. Contribute to our research on the development landscape.

Take the survey

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay