Ruben Kannan
Ruben Kannan

Reputation: 330

Parsing XML on a Google Apps script

Here's my XML:

<?xml version="1.0" encoding="UTF-8" ?> 
<response>
    <records>
        <record id='1'>
            <column name="Name"><value><![CDATA[John]]></value></column>
            <column name="Email"><value><![CDATA[[email protected]]]></value></column>
        </record>
        <record id='2'>
            <column name="Name"><value><![CDATA[Joe]]></value></column>
            <column name="Email"><value><![CDATA[[email protected]]]></value></column>
        </record>
    </records>
</response>

And, here's my attempt to parse the above XML and return Name and email as arrays:

var document = XmlService.parse(the_above_xml);
var root = document.getRootElement();
var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
var records_all = document.getRootElement().getChildren('records', atom);
for (r=0; r<records_all.length; r++){
    var records = records_all[i].getChildren('record', atom);
    for (i=0; i< records.length; i++){
        columns = records[i].getChildren('column', atom);
        for (c=0; c< columns.length; c++){
            // I'm stuck here. I want to return an array of name and emails. 
        }
    }
}

I was going through https://developers.google.com/apps-script/reference/xml-service/ and couldn't figure out how to achieve it. How can I fix it?

Upvotes: 1

Views: 5301

Answers (1)

Bardy
Bardy

Reputation: 2170

How about:

function getRecords(xml) {
  var xmlDoc = XmlService.parse(xml);

  var response = xmlDoc.getRootElement();
  var records = response.getChild('records');
  var recordList = records.getChildren('record');

  var output = [];
  for (var i = 0, record; record = recordList[i]; i++) {
    var columnList = record.getChildren('column');
    var name = '';
    var email = '';
    for (var j = 0, column; column = columnList[j]; j++) {
      var attrName = column.getAttribute('name').getValue();
      var text = column.getChild('value').getText();
      if (attrName === 'Name') {
        name = text;
      } else if (attrName === 'Email') {
        email = text;
      }
    }
    output.push([name, email]);
  }
  return output;
}

This function takes a string argument, being your XML, and returns a two-dimensional array, with each row of the array being name and email address pairs.

Upvotes: 1

Related Questions