XML changes in Apps Script

Many developers have come to prefer JSON for data serialization, but we recognize that good ol' XML is still an important format for many Apps Script users. Our existing XML service is good at parsing XML, but has limited ability to create or alter existing documents. In order to provide a more complete and consistent experience, we have created a new XML service, which launches today. The new service is accessed using XmlService, in contrast to the old service which was simply called Xml.

Let's take a look at how you can use the new service to create an XML representation of the emails in your Gmail inbox.

function createXml() {
var root = XmlService.createElement('threads');
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++) {
var child = XmlService.createElement('thread')
.setAttribute('messageCount', threads[i].getMessageCount())
.setAttribute('isUnread', threads[i].isUnread())
.setText(threads[i].getFirstMessageSubject());
root.addContent(child);
}
var document = XmlService.createDocument(root);
var xml = XmlService.getPrettyFormat().format(document);
Logger.log(xml);
}

The code above logs XML that looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<threads>
<thread messageCount="1" isUnread="true">
Can't wait for the new XML service!
</thread>
<thread messageCount="1" isUnread="true">
50% off all widgets through Friday
</thread>
<thread messageCount="3" isUnread="false">
Don't forget about the picnic on Saturday
</thread>
</threads>

The new XML service has some notable advantages over the old service:

  • The ability to alter parsed XML content and save it back to a string.
  • Access to all entity types in the XML document (CDATA sections, Comments, etc.)
  • More control over the formatting of the XML string.

With the launch of this new service, we are deprecating some of our older XML tools in Apps Script, specifically the old XML service, the SOAP service, and the JavaScript feature E4X. Calls to these services will continue to work, but we encourage you to start migrating your code to the new XML service for better long-term support. On February 1, 2014, these old services will no longer appear in auto-complete or in our documentation, per the Apps Script sunset schedule.