Skip to content Skip to sidebar Skip to footer

How Can I Get The Element Id From XML Parse In Google Apps Script

Xml Code
Display name
<

Solution 1:

  • You want to retrieve 123 and 160 from the following xml data.

      <directory>
        <fieldset>
          <field id="displayName">Display name</field>
        </fieldset>
        <employees>
          <employee id="123">
            <field id="displayName">John Doe</field>
          </employee>
          <employee id="160">
            <field id="displayName">Jane Doe</field>
          </employee>
    
  • You want to achieve this using XmlService of Google Apps Script.

Modification point:

  • In your case, roots retrieves employee. So using this, you can retrieve the attribute of id.

Modified script:

When above xml data is used, the sample script is as follows. In this sample, </employees></directory> is added to the sample xml data.

function myFunction() {
  const xml = `<directory>
  <fieldset>
    <field id="displayName">Display name</field>
  </fieldset>
  <employees>
    <employee id="123">
      <field id="displayName">John Doe</field>
    </employee>
    <employee id="160">
      <field id="displayName">Jane Doe</field>
    </employee>
  </employees>
</directory>`;
  var document = XmlService.parse(xml);
  var roots = document.getRootElement().getChild('employees').getChildren();
  var ids = roots.map(e => e.getAttribute("id").getValue());
  console.log(ids);  // [123, 160]
}

Note:

  • In this case, please use the script with V8.

  • If you want to retrieve both id of employee and the value of field, you can also use the following script.

      var ids = roots.map(e => ({id: e.getAttribute("id").getValue(), name: e.getChild("field").getText()}));
    
    • In this case, [ { id: '123', name: 'John Doe' }, { id: '160', name: 'Jane Doe' } ] is retrieved.
  • When the structure of above xml sample data is different from your actual data, the modified script might not work. So please be careful this.

Reference:


Solution 2:

(function() {
   var roots =document.getElementsByTagName("employees")[0].children;
   
   for(k=0;k<roots.length;k++){
    var id=roots[k].getAttribute("id")
    console.log(id);
   
   }
   
   

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<directory>
 <fieldset>
  <field id="displayName">Display name</field>
 </fieldset>
 <employees>
  <employee id="123">
   <field id="displayName">John Doe</field>
  </employee>
  <employee id="160">
   <field id="displayName">Jane Doe</field>
  </employee>
  </employees>
 </directory>

you can access id like this using javascript


Post a Comment for "How Can I Get The Element Id From XML Parse In Google Apps Script"