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.