XML Shenanigans

PUBLISHED ON FEB 9, 2015 — IMPORTED FROM TUMBLR, TEXT

For the last couple of weeks, I’ve been working on a project at work that has involved, among other things, parsing XML and updating existing XML files. Just like every other time I have to deal with XML, I do two things:

  1. Throw up a little bit.
  2. gem install nokogiri

I found lots of code samples, including in the Nokogiri tutorials, that discussed how to create a new node and then insert a string as the node contents. This would have been ok if my node contents didn’t contain more nodes. Nokogiri tried to be helpful and escaped the node contents. So, not very many < and >, but lots of &gt; and &lt;.

D'oh.

I eventually came across this snippet:

Nokogiri::XML::DocumentFragment.parse(thing_to_add)

It takes an XML-ish string and reformats it, making it ready to insert into the XML document. Take a look at the following gist for a version of the method I used for my assignment: