"Using JavaScript to differentiate between elements with the same name in

I am dealing with an XML file that contains multiple instances of the same element name, as shown below. I am currently only able to retrieve the first occurrence and would like to know how to access all 4 "comments" using JavaScript. Thank you!

<FRIENDSSTATUS>
  <STATUSFRIENDS id="2">
    <STATUS>Life begins at the end of your comfort zone</STATUS>
    <DATETIME>2012-10-30 10:32:28</DATETIME>
    <FIRSTNAME>Malcolm</FIRSTNAME>
    <LASTNAME>Landgraab</LASTNAME>
    <COMMENTS datetime="2012-11-18 22:13:28" firstname="Ian" lastname="Tellerman">rr</COMMENTS>
    <COMMENTS datetime="2012-11-18 22:13:39" firstname="Ian" lastname="Tellerman">hello</COMMENTS>
    <COMMENTS datetime="2012-11-19 14:36:24" firstname="Ian" lastname="Tellerman">test</COMMENTS>
    <COMMENTS datetime="2012-11-19 14:45:52" firstname="Ian" lastname="Tellerman">test4</COMMENTS>
   </STATUSFRIENDS>
  <STATUSFRIENDS id="3">
    <STATUS>Prometheus. Fantastic film!!!!</STATUS>
    <DATETIME>2012-10-30 10:32:28</DATETIME>
    <FIRSTNAME>Mansa</FIRSTNAME>
    <LASTNAME>Bendett</LASTNAME>
    <COMMENTS datetime="2012-11-18 22:14:46" firstname="Ian" lastname="Tellerman">wrong</COMMENTS>
  </STATUSFRIENDS>
</FRIENDSSTATUS>

Below are the javascript codes for retrieving the data:

xmlDoc = xmlhttp.responseXML;
$table = "<table border='1'>";

var element = xmlDoc.getElementsByTagName("FRIENDSSTATUS");
var elements = xmlDoc.getElementsByTagName("STATUSFRIENDS");
var comments = xmlDoc.getElementsByTagName("COMMENTS");

if(xmlDoc.documentElement !== null){

var root;
if (navigator.userAgent.indexOf("Firefox") > 0)
var root = element[0].childElementCount;

if (navigator.userAgent.indexOf("MSIE") > 0)
var root = xmlDoc.documentElement.childNodes.length;

for(i=0; i<root; i++){
$strStats = "";
$strComments = "";
$strDateTime = "";
$strFirstname = "";
$strLastname = "";

$strCommentDateTime = "";
$strCommentFirstName = "";
$strCommentLastName = "";
$strStatusID = "";

if(navigator.userAgent.indexOf("Firefox") > 0){
for(y=0;y < elements[i].childElementCount;y++){

 $strStatusID = elements[i].getAttribute("id");
 if(strStatus = elements[i].getElementsByTagName("STATUS")){
    $strStats = strStatus[0].firstChild.nodeValue; 
 }

 if(strStatus = elements[i].getElementsByTagName("DATETIME")){
    $strDateTime = strStatus[0].firstChild.nodeValue; 
 }

 if(strStatus = elements[i].getElementsByTagName("FIRSTNAME")){
    $strFirstname = strStatus[0].firstChild.nodeValue; 
 }

 if(strStatus = elements[i].getElementsByTagName("LASTNAME")){
    $strLastname = strStatus[0].firstChild.nodeValue; 
 }
 if(strComm = elements[i].getElementsByTagName("COMMENTS")){ 
    $strComments = strComm[0].firstChild.nodeValue;
    $strCommentDateTime = comments[i].getAttribute("datetime");
    $strCommentFirstName = comments[i].getAttribute("firstname");
    $strCommentLastName = comments[i].getAttribute("lastname");
    $strComments += "<br>" + $strCommentFirstName + " " + $strCommentLastName + " " + $strCommentDateTime + "</br></br>";
}
$strStats = $strStats + " " + $strLastname + " " + $strFirstname + " " + $strDateTime;
$strFullName = $strFirstname + " " + $strLastname;
$strDateTime = "";
$strFirstname = "";
$strLastname = "";
}
}

Answer №1

To store your XML data, create a variable named myXmlString. You can then access and manipulate it like so:

var parser=new DOMParser();
doc=parser.parseFromString(myXmlString,'text/xml');
var comments = doc.getElementsByTagName("COMMENTS") // This will retrieve an array of the comment elements.

Answer №2

A demonstration showcasing how to retrieve the comments from the initial STATUSFRIENDS element can be seen in this jsFiddle example.

var parseXmlData;

if (typeof window.DOMParser != "undefined") {
    parseXmlData = function(xmlString) {
        return ( new window.DOMParser() ).parseFromString(xmlString, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXmlData = function(xmlString) {
        var xmlDocObject = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDocObject.async = "false";
        xmlDocObject.loadXML(xmlString);
        return xmlDocObject;
    };
} else {
    throw new Error("No XML parser available");
}

var xmlSource = parseXmlData(xmlString); // assuming xmlString contains the XML content
var commentsCollection = xmlSource.documentElement.childNodes[0].getElementsByTagName("COMMENTS");
var results = "";

for(var j=0; j<commentsCollection.length; j++)
{
   results += commentsCollection[j].firstChild.nodeValue + "<br />";   
}

document.getElementById("commentsOutput").innerHTML = results;

Answer №3

Here's an example:

let data = 'your JSON data as a string',
    parsedData;

try {
    parsedData = JSON.parse(data);
}
catch (error) {
    console.error('Error parsing JSON data:', error);
}

if (parsedData) {
    let items = parsedData.items,
        total = 0;

    for (let item of items) {
      total += item.price;
    }

    console.log('Total price:', total);
}

Answer №4

Unfortunately, I am unable to provide a complete code sample at this time, but JavaScript does have support for XPath which allows you to fetch Comments using the following Qpath query:

/FRIENDSSTATUS/STATUSFRIENDS[@id="3"]/COMMENTS

If you want to test the Xpath syntax, you can do so by visiting:

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

A step-by-step guide on dynamically utilizing ng-outlet in AngularJS

For the past couple of days, I have been immersed in developing an AngularJS app. After two days of brainstorming, I have finally grasped how to utilize AngularJS's new router with components and ng-outlet feature. However, just when I thought everyt ...

You may encounter issues with invoking methods on a JavaScript object in Node.js after using res.send for response sending

Exploring Context and Design Overview Currently, I am utilizing a library known as Tiff.js to seamlessly load Tiff images on a designated webpage. The usage of this library extends both to the server-side and client-side functionalities. On the server end ...

Guide: Communicating with child component functions from parent component in React/Typescript

I am facing an issue while trying to utilize the child component function "changeName" in a parent component. The error message I receive is: Property 'superheroElement' does not exist on type 'App'. How can I resolve this issue effecti ...

Error message: A function is being utilized with an undefined variable

Within my PHP code, I am passing a variable to a function. The code works fine when I use an HTML select tag: <span id="opinion"> <select name="" id="" STYLE="width: 300px" onchange="get_opinion(this.value)"> < ...

Creating a row in a table based on the selected text field

I've set up a table on my html page with each cell containing a form field corresponding to the title. At first, there are only two rows visible in the image below. To add another row dynamically when the first form element in the last row is clicked ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...

Change Scenery by Using Arrow Keys

I am trying to increase the speed of my background when the up and arrow keys are pressed. Despite my attempts, it is not working as expected. The variable this.speed controls the speed of the background. To achieve this, I implemented an if statement t ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

Issues with JQuery Beginner using the .after Method

Can you help me figure out what's wrong with this code snippet? I've double-checked the path to the JavaScript file and it seems correct, so I suspect there might be an issue within the code itself. The inserted paragraph is not being displayed a ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

Implementing interactive elements such as buttons and controls on an HTML5 canvas

I've been working with the three.js 3D engine and I'm wondering how to incorporate UI buttons onto my WebGL canvas. Any ideas on how to achieve this? ...

What steps can be taken to restrict a user's access to a route through URL parameters?

I am currently developing an Express application that generates and exports a document based on the selections made by a user from two dropdown menus. The values selected in the dropdowns are passed as route parameters after the user clicks a button, trigg ...

Is there a way to extract the year, day, minute, hour, and second from the Date.now() function in Node.js?

Figuring out how to interpret Date.now() has been challenging for me. I understand that it returns the time in milliseconds since the unix epoch (January 1st, 1970), but I'm struggling to use this information to determine the current date and hour. An ...

Discovering if a value has been entered into an input field in AngularJS can be achieved by verifying its availability

Is there a way to check if the value entered in an input field is already in a specified array? I would like to validate the input field value on key press against an array of names and display an error message if the value is already present in the array. ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...

Is the model returned by the Mongoose .findOne method in case of an error?

Currently, I am facing an issue while attempting to access an account using the findOne function in mongoose. When I try to console.log the error, it only displays that the correct model has been found. Once I locate the correct model, my intention is to a ...

Incorporating an HTML file into a DIV container while also displaying menu links

I am facing a major challenge with what I recognize as a relatively simple issue for experts. As someone who is still learning, I am struggling to create menu links that load an HTML file into a specific DIV. Despite my efforts, the content keeps loading i ...

How to Send C# Array as a Parameter to a JQuery Function

I'm currently working on passing a C# array to a JQuery function as a parameter. The C# code I have to call the function is: //Create an Array from filtered DataTable Column var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r ...

Retrieve "N/A" values for any vacant spaces in the lxml xpath() function

Here is a sample of a large XML file that I am working with, which can be accessed here: <?xml version="1.0" encoding="UTF-8"?> <hmdb xmlns="http://www.hmdb.ca"> <metabolite> <n ...