An unexpected issue occurred while converting XML data into JSON format

I have been using a piece of code that converts XML to JSON:

// Converting XML to JSON
var XmlToJson = function xmlToJson(xml) {
    //console.log('called xmltojson');
    //console.log(xml);
    // Creating the return object
    var self = this;
    var obj = {};

    if (xml.nodeType == 1) { // element
        // handle attributes
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }

    // handle children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};

module.exports = XmlToJson;

Here is a sample XML input:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>asdf</string>
<string>123</string>
<string>zxcv</string>
<string>qwer</string>
<string>werty</string>
<string>dfgh</string>
<string>rytui</string>
</ArrayOfstring>

This would result in the following output:

When inspecting the object in Chrome Console I see:

Object {Arrayofstring: Object}
  ArrayOfString: Object
    @attributes: Object
    string:  Array[7]
      0:  Object
        #text: "123"
      1:  Object
        #text: "456"

I am facing difficulty in accessing the #text data. Is it correct to have a hash character in a variable name? How can I access the value of these #text parameters?

I attempted various methods like:

console.log(myVariable.string[0]);

However, all the variations I tried resulted in undefined.

Answer №1

The variables labeled as #text are directly from text nodes within the DOM (nodeType = 3) and are identified by the special type "#text".

If I enter the following commands in my browser console:

> var y = {};
< undefined
> y['#text']= '1234';
< "1234"
> y
< Object { #text: "1234" }
> y['#text']
< "1234"

Based on your scenario (assuming I understand the object and its descendants correctly):

console.log(objName.Arrayofstring.string[0]['#text'])

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

Identifying CMYK Images Through Javascript Feature Detection

Many are aware that IE8 does not support CMYK JPG images, as it fails to render them at all. This post discusses the issue further: , among others. My inquiry is as follows: Is there a method to detect from JavaScript, akin to Modernizr, whether a browse ...

Accessing variables in subfunctions proves challenging for Node.js

Here is a function I've been working on to calculate the total price for a checkout process. However, when I console.log() the variable before it is returned, I get 0. But if I log the variable inside the findOne() function, I get the correct value. ...

Having trouble getting the jQuery/JS redirect button to function properly

I'm fairly new to working with jQuery. My current challenge involves unsetting a cookie and then navigating to the next page. There are numerous resources discussing this topic online, but what seemed like a simple task has turned into a two-hour hea ...

How to effectively implement addEventListener() / attachEvent()?

Can anyone provide guidance on how to correctly use addEventListener and attachEvent? window.onload = function (myFunc1) { /* do something */ } function myFunc2() { /* do something */ } if (window.addEventListener) { window.addEventListener('load ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

Monitoring the modifications of a linked component in React: A guide

I am facing an issue where I need to store the text of a referenced element in an array. My goal is to first display the text of each paragraph element with the "ebookName" class in the console before storing it in the array. However, I have encountered a ...

JavaScript Empty Input Field when Duplicating Node

I am seeking advice on how to clear the textboxes when an HTML form is cleared. The following JS code runs onclick: var counter = 0; function moreField() { counter++; var newFields = document.getElementById('readroot').cloneN ...

User form not triggering post requests

I have a unique react blog application embedded with a form for submitting intriguing blog posts. The setup includes a server, routes, model, and controllers for fetch requests. Surprisingly, everything functions impeccably when tested on Postman. However, ...

Significant delay in fetching model data for controller via XHR

My controller is designed to make an ajax call to retrieve its model, which is a 4.5k json containing a 2d array. This data is then used to create a combo displaying a series of labels in the html below: <select data-ng-controller="CGSimpleXHRComboCont ...

The success of a jquery ajax call always seems to elude me as it consistently throws

I've been facing an issue with my code snippet. The problem lies in the fact that the function on success is never executed; instead, it always triggers the error section. $.ajax({ url: 'http://localhost/zd/get_list', data: 'ter ...

How can the client be informed about the ongoing processing of the request by the servlet?

In my web application, I have JS/jQuery on the front end and servlets on the back end. When making a request to a servlet, it performs multiple tasks in one call (such as executing a shell script that runs various Python scripts). My main query is whether ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Executing multiple setTimeout calls simultaneously can result in greater delays than anticipated

During my exploration of Node performance, I encountered an unexpected issue where an example involving 50 concurrent calls to setTimeout took over 4 seconds instead of the anticipated 500ms. The scenario involves a basic express server that waits for all ...

"Troubleshooting Problem with JSON Encoding in PHP and Parsing with getJSON in

Apologies if this sounds like yet another discussion on the topic, but I've been struggling for hours without finding a solution. I'm attempting to retrieve data from a MySQL database, generate a JSON using PHP, and then parse this JSON in JavaS ...

Why does Jquery refuse to accept hyphens in the JSP page?

I received a field from SERVICE that contains a hyphen. For example, first-name (as a JSON object). However, when I attempt to retrieve the value of this field in my JSP file, I encounter a script error. Can you please advise me on how to properly access ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

What is the best way to retrieve JSON data responses in Objective-C?

I am sharing my information via URL using the following code block. NSString *urlString = [NSString stringWithFormat:@"company_name=%@&email_id=%@&password=%@",_CompanyName.text,_Email.text, _Password.text]; NSString *postLength = [NSString string ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...