JavaScript for Extracting Child Elements from XML

Below is the XML format I am working with:

<Result>
    <system>
      <STATIC>
       <Tag1>2015-10-29T02:02:38-08:00</Tag1>
       <Tag2>264000000</Tag2>
       <Tag3>32696320</Tag3>
      </STATIC>
    </system>
</Result>

I attempted to parse the child elements using the code below:

 if(window.DOMParser)
 {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(res,"text/xml");
 }
 else // Internet Explorer
 {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.loadXML(res);
 }

var result=xmlDoc.getElementsByTagName("Result"); // Result child

For the system child, I tried:

var system=result[0].childNodes[0];

However, when I attempted to get the <system> tag's child, an error occurred:

var staticResp=system[0].childNodes[0];

Error : Uncaught TypeError: Cannot read property 'childNodes' of undefined(…)

Could someone please assist me in retrieving the child of the <static> tag and its value using the tag name?


Thank you for the prompt replies.

After receiving the above XML data in an AJAX response, I noticed some special characters like &#13;&#10; after the system tag.

It seems that the proposed solutions may not work for my case.

Can anyone offer assistance on how to ignore these special characters and successfully parse the string?

Here is the captured XML:

<Result><system>&#13;&#10; <STATIC>&#13;&#10; <Tag1>2015-10-29T02:02:38-08:00</Tag1>&#13;&#10; <Tag2>264000000</Tag2>&#13;&#10; <Tag3>32696320</Tag3></STATIC>&#13;&#10; </system></Result>

Answer №1

You can utilize the method .getElementsByTagName to retrieve elements by their tag name, eliminating the need for childNodes

var xmlData = 
    '<Result>' + 
    '<system>' + 
    '<STATIC>' +
    '<Tag1>2015-10-29T02:02:38-08:00</Tag1>' +
    '<Tag2>264000000</Tag2>' + 
    '<Tag3>32696320</Tag3>' + 
    '</STATIC>' +
    '</system>' + 
    '</Result>';

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlData, 'text/xml');

var result = xmlDoc.getElementsByTagName('Result');

var static = xmlDoc
  .getElementsByTagName('system')[0]
  .getElementsByTagName('STATIC')[0];

console.log(static.getElementsByTagName('Tag1')[0].innerHTML);
console.log(static.getElementsByTagName('Tag2')[0].innerHTML);
console.log(static.getElementsByTagName('Tag3')[0].innerHTML);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Answer №2

network consists of a single node rather than an array of nodes. You can attempt accessing it using

var dynamicNode = network.childNodes[0];

Example

Answer №3

getElementsByTagName() retrieves an HTMLCollection. Here's a way to use it:

var staticResp = doc.getElementsByTagName('STATIC')[0];

var xmlText = '<Result>\
    <system>\
      <STATIC>\
       <Tag1>2015-10-29T02:02:38-08:00</Tag1>\
       <Tag2>264000000</Tag2>\
       <Tag3>32696320</Tag3>\
      </STATIC>\
    </system>\
</Result>';

var parser = new DOMParser();
var doc = parser.parseFromString(xmlText, "application/xml");
var staticResp = doc.getElementsByTagName('STATIC')[0];

for(var i = 0; i < staticResp.children.length; i++){
    snippet.log(staticResp.children.item(i).tagName);
}
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

making changes to a {{ variable }} within the directive's template

I am having trouble understanding how to properly set a {{ variable }} in my directive template. Currently, the only way I can update it is by using $scope.$apply(), specifically for updating the current-time text in a video player. You can view my code e ...

Guide to creating a cryptosystem using a Synchronous Stream Cipher with Vue js

I am currently working with a pseudo-random number generator that creates binary numbers using a user-supplied polynomial and the LFSR method. To enhance the process, I need to convert a loaded file into binary format so that I can apply the XOR operatio ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Leverage the power of React by utilizing SVGR to easily integrate SVG files

Wondering if there's a way to bring in an SVG file from my public folder and use it as a React component like this: import { ReactComponent as MySvg } from '/assets/svg/mysvg.svg'; const MyComponent = () => { return ( <div> ...

How can I utilize jQuery to iterate through every anchor tag on an HTML page?

I am looking to reference all anchor tags on the page that have a parent h2 tag. To achieve this, I need to iterate through each anchor tag that has a parent h2 and add an attribute using jQuery. <body> <h1>not me</h1> <a href ...

Error: jQuery JSONP syntax error due to missing semicolon before statement

Currently, I have implemented the following code to access a rest service that is hosted on a different domain: $.ajax({ type: 'GET', url: url, async: false, jsonpCallback: 'jsonCallback' ...

Incorporate several websites into a React application without using iframes

After developing a React application with create-react-app, I attempted to embed another website onto the app using an iframe. Everything worked perfectly until I wanted to resize the iframe to fit the page, resulting in a Blocked a frame with origin from ...

Include dropdown lists for selecting the year, month, and day on a web page

Is there a way to implement a dropdown style date selector that dynamically updates the number of days based on the selected year and month using JavaScript? For example, February 2008 has 29 days, April has 30 days, and June has 31 days. Any suggestions ...

Provide Jquery with a named function for success plus some extra perplexity

Can anyone help me figure out why my JQUERY .ajax request won't accept a non-anonymous function in the success condition? I prefer not to use anonymous functions because I find them harder to debug and read. I've also heard that breaking out fun ...

Calculate the sum of input values in a JavaScript function with the same class

Can anyone help me figure out how to sum the values of input fields with the same class? I've attempted the code below but it doesn't seem to be working. Any ideas on what I'm doing wrong? <table id="tableID"> <tr> <td> ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

What is the method for altering the track color on a range slider?

Struggling to change the track color of a range slider using CSS in Chrome? Look no further, as I found a solution using jQuery (link). However, after implementing the solution, the expected output is not achieved. jQuery: $('.text-size-slider .slid ...

Working with NodeJS: Utilizing object casting with default values and eliminating superfluous

In the backend code of a NodeJS application, there is an object defined as follows: { name : "foo" secret : "bar" } The objective is to return this object as JSON in response to an HTTP request without including the secret key. The desired return obj ...

Updating multiple elements in the DOM simultaneously

I'm attempting to update placeholders for values in a form if Internet Explorer is version 9 or 8. I have the following code snippet: if( $("html").data("version") == "IE9-10" ){ var brand = $(".brand input"); var value = brand.attr(" ...

Utilizing Mongoose's `sava()` method, check if the document exists; if not, create a new

Every 1 second, my mongoose schema saves data. If the data already exists, it updates that document. this.sub.on('message', async function (topic, message) { const soilesensor = new SensorModel({ topic: topic, value: parseFlo ...

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? https://i.sstatic.net/Hk591.png ...

Transforming Danish currency into numerical digits effortlessly

My current currency is 3.477,60 kr and I need to incorporate it into my JavaScript code for additional price calculation logic. I have tried using the following code to format it, but unfortunately, it returns NaN in the alert message. var currency = "3. ...