There are a few examples of XML to JSON conversion around, but not so many going the other way. In case you need to convert Apps Script objects to XML, here’s a snippet to do it. Actually, there are two approaches shown here, as dealing with Arrays is not an exact science in XML. I prefer the second of the solutions shown. You can find the opposite of this over at From Xml to JSON

There is now a webapp api of this too which you can use to convert online. See Using Apps Script for xml json conversion

How to use

Let’s start with this JavaScript object that we need to convert to XML for some inexplicable reason. It contains examples of most of the type of things you’d need to create. All the values will be converted to text nodes, without attributes.

It can be used like this

The result

This uses the tag element to indicate a member of an array. The second solution on this page takes a different (and better approach).

The code

It’s recursive, so in the end it’s just a few lines of code.

An alternative approach.

Arrays are funny things in XML, since they are identified by a repetition of a tag, rather than being specifically called out as an array as they are in JSON. In the example above, I’ve inserted a new tag to identify elements of an array. The problem with this approach is that the JSON is not reversible back to XML – since new tags have been inserted. A better approach is to use the Array key as the tag to be repeated.

and the result using the modified approach

This makes xml that can be reversed back out to JSON, and makes a better solution in my opinion, except that arrays with just 1 member are not distinguishable as arrays.

For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.