What is the method to extract the Element Id from XML parsing in Google Apps Script?

Sample Xml Code

<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>

Using XmlService.parse to retrieve content within each element works fine, but there seems to be an issue with extracting the employee/element id numbers

After running this code snippet:

var roots = document.getRootElement().getChild('employees').getChildren();

The individual elements are retrievable, however, there is difficulty in obtaining the id's

 [[Element: <employee/>], [Element: <employee/>], [Element: <employee/>],...

Answer №1

  • To extract data from the given xml, you need to retrieve 123 and 160.

      <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 can achieve this task using XmlService in Google Apps Script.

Key point:

  • The script uses roots to fetch employee, allowing you to access the id attribute.

Modified code snippet:

When working with the provided xml data, here is a sample script including the closing tags

</employees></directory>
.

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:

  • Make sure to run the script with V8 for optimal performance.

  • If you also wish to retrieve the value of field along with the id of each employee, refer to the additional script below.

      var ids = roots.map(e => ({id: e.getAttribute("id").getValue(), name: e.getChild("field").getText()}));
    
    • This will return
      [ { id: '123', name: 'John Doe' }, { id: '160', name: 'Jane Doe' } ]
      .
  • Please be cautious if the structure of your actual xml data differs from the provided example, as it may impact the functionality of the modified script.

For more information:

Answer №2

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

})();
<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>

Accessing the employee ids through JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Smoothly scroll through parallax backgrounds

I've implemented a feature where an element moves in relation to scrolling using jQuery: $('#object').css('transform','translateY('+($(window).scrollTop()*.4)+'px)'); Here's the CSS: #object { width: ...

"Encountering a restricted URI error when attempting to load a text file using AJAX

After reviewing the recommended link, I found myself struggling to grasp the suggestion to "Use Greasemonkey to modify Pages and start writing some javascript to modify a web page." Currently, I am encountering an error when loading a text file using $.aj ...

Ways to ensure the synchronous execution of asynchronously invoked functions

I'm currently navigating the world of asynchronous code and trying to grasp its workings. As I construct a Node Express application that interfaces with a database, my aim is for it to interact with a Sqlite database in a development setting. (The pr ...

Presenting the output of a machine learning model on a website

Currently, I am delving into RESTful Flask API and to enhance my learning experience, I decided to create a compact web form using HTML. Below is the snippet of code for the HTML form. <!DOCTYPE html> <html> <h2>User Input</h2> < ...

Can the unacknowledged range-based for loop be identified?

What is causing this error message to be generated by the following code snippet: void printarray(int array[]) { for (int x: array) { std::cout << x << std::endl; } } Specifically, why does it say: error: 'begin' wa ...

Javascript splice method mistakenly eliminating the incorrect elements

I have an array of objects like the one below: [{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}] These objects are indexed as follows: [0, 1, 2]. I'm attempting to delete an item at a specific position using this code: $scope.selectedSound ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Tips for waiting on image loading in canvas

My challenge involves interacting with the image loaded on a canvas. However, I am uncertain about how to handle waiting for the image to load before starting interactions with it in canvas tests. Using driver.sleep() is not a reliable solution. Here is ...

Unexpected issue: THREE js Object position does not update after rotation

For the past couple of weeks, I've been engrossed in creating a solar system model using Three.js. After following tutorials and documentation, I successfully created a working model of the solar system. However, I encountered an issue when trying to ...

Ensure that the children elements can be resized without exceeding the boundaries

My goal is to ensure that the resizable elements stay within their parent element. What I tried: I have set the minHeight : property and while resizing, I am using Math.max to limit the height to 30px. Expected Result: All resizable child elements sh ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Discovering the origin of an unexpected element.style manifestation

I cannot figure out how this strange issue occurred. This is the correct HTML code structure: <nav class="navbar navbar-inverse navbar-fixed-top"> However, Chrome is displaying the following unexpected code: <nav class="navbar navbar-invers ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Issue arises when attempting to compare this specific data type as a string

When attempting to retrieve the index of a string in an array using string index_of(string value, string data[], int size), I encountered errors during compilation with the provided code. string index_of(string value, string data[], int size) { for( ...

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...

Exporting Canvas data without the alpha channel

I am looking for a way to resize images that are uploaded in the browser. Currently, I am utilizing canvas to draw the image and then resize it using the result from the toDataURL method. A simplified version of the code (without the upload section) looks ...

Splitting with Regex - One Time Operation

Here is some of my Jquery code along with Regex: $("[class^=ipsum-img],[class^=ipsum-img-]").each(function(){ var x = $(this).attr("class"); console.log(x.length); if (x.length>8) { var m = x.split(/(\d+)[^-]*$/g); cons ...

Detecting Pixel Colors Across Multiple Overlapping Canvases

I have a challenge with multiple canvas elements on my webpage. I am trying to retrieve the pixel color of all overlapping canvas elements when they are stacked on top of each other. Let me illustrate with an example below. In this scenario, I am attempt ...

Tips for modifying the color of a query term in HTML

Within my HTML file, I have <p class = "result"> {{searchResult}} </p> where {{searchResult}} represents the result of a search term. If I search for the term "hot", {{searchResult}} would display a string containing the word "hot" in a ...