Search code examples
javascriptxmlgoogle-apps-scriptatom-feedatompub

How to extract value from AtomPub XML HTTP response in Javascript (for Google Apps Admin Settings API)


I am calling the Google Apps Admin Settings API from a Google Apps Script script (Javascript) to retrieve the maximum number of users in our Google Apps domain.

A successful GET request returns the response in AtomPub XML format, like so:

<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'>
<id>https://apps-apis.google.com/a/feeds/domain/2.0/domain.com/general/maximumNumberOfUsers</id>
<updated>2014-07-16T00:55:27.837Z</updated>
<link rel='self' type='application/atom+xml' href='https://apps-apis.google.com/a/feeds/domain/2.0/domain.com/general/maximumNumberOfUsers'/>
<link rel='edit' type='application/atom+xml' href='https://apps-apis.google.com/a/feeds/domain/2.0/domain.com/general/maximumNumberOfUsers'/>
<apps:property name='maximumNumberOfUsers' value='100'/></entry>

The value of the maximumNumberOfUsers property (in this case it's 100) is the only part I care about.

How do I extract that value so I can assign it to an integer variable?

My first instinct was to write a crazy complex regex but I KNOW there must be an easier way!

I think there's a way to do this with JQuery, but there's no way to use jQuery in Google Apps Script.


Solution

  • Read over this previous answer. No need to write crazy regex... just pick up that utility that deals with the xml structure directly!

    Here's an untested piece of code that uses the getElementByVal() function from that answer:

    ...
    var xml = UrlFetchApp.fetch(url).getContentText();
    var document = XmlService.parse(xml);
    var root = document.getRootElement();
    var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
    var entries = document.getRootElement().getChildren('entry', atom);
    
    var maxUsers = getElementByVal( entries, 'property', 'name', 'maximumNumberOfUsers' );
                        .getAttribute(value);
    ...