One-liner XML / Perl / JSON

castaway blew my mind this morning in #axkit-dahut.

Convert an XML file to Perl data structure:

perl -MXML::Simple -MData::Dumper -le'print Dumper XMLin("foo.xml")'

Convert an XML file to JSON:

perl -MJSON::Any -MXML::Simple \
   -le'print JSON::Any->new()->objToJson(XMLin("foo.xml"))'

"How do I do X?" Like this! Poof!

Some days Perl feels like a Las Vegas magic show. :)


Yes, Perl is nice. But not unique in this regard. For example in Ruby you can also do:

# Convert XML to Ruby data structure
ruby -rxmlsimple -rpp -e'pp XmlSimple.xml_in( "foo.xml")'

# Convert XML to JSON
ruby -rxmlsimple -rjson -e'puts XmlSimple.xml_in( "foo.xml").to_json'

You probably want to do XMLin("foo.xml", KeepRoot => 1, ForceArray => 1, KeyAttr => []) instead, if you want the data to have a consistent structure.

@Steve - However, this is a Perl blog not a Ruby one.

And please don't take that comment in a bad was not meant to be.

Yup, sorry for being a party pooper. No bad way taken.

Perhaps I just wanted to remind us that unlike say 10-15 years ago many languages have caught up with Perl (and even surpass it in some ways). Cool libraries like XML::Simple, LWP, WWW::Mechanize, etc are also available in some form or another in other languages too. And that's not a bad thing, because these languages also pressure Perl to improve further (case in point, cpanminus).

Add css selectors, and using only one module with no dependencies:

cat file.xml | perl -MMojo::DOM -e 'print Mojo::DOM->parse(<STDIN>)->at("div.links > a[href]")'

Or even better:

perl -Mojo -E'g("")->dom("a.story-title")->each(sub { say shift->text })'

Leave a comment

About Jay @ Mutation Grid

user-pic Perl / web / database development since 1995. Contact us for your next project.