0

I am parsing xml file in javascript and i am extracting all its values

function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  myFunction(this);
}
};
xmlhttp.open("GET", "/ccm/rpt/repository /workitem?fields=workitem/projectArea/*", true);
xmlhttp.send();
}

function myFunction(xml) {
var x,y,j, i, xmlDoc, txt,txt1;
xmlDoc = xml.responseXML;
txt = "";
txt1="";
x = xmlDoc.getElementsByTagName("contextId");
for (i = 0; i< x.length; i++) {
txt += x[i].childNodes[0].nodeValue;

}
y = xmlDoc.getElementsByTagName("name");
for (j = 0; i< y.length; j++) {
txt1 += y[j].childNodes[0].nodeValue;
}
}

and now my target is to store the value of name as key and contextId as value (HashMap concept) , So is it possible to achieve the same,Also please let me if my question sounds ambiguous Thanks in advance!!

1 Answer 1

1

You can add properties to objects as if they were hashmaps, have a look at this example:

var myObj = {prop1: 12};
var propName = "prop2";

myObj[propName] = 10;

console.log(myObj);

Which outputs:

{prop1: 12, prop2: 10}

In your example, lets assume x and y are of equal length, then we can add to the object in a single loop:

var x,y,j, i, xmlDoc, myHashMap;

xmlDoc = xml.responseXML;
myHashMap = {};

x = xmlDoc.getElementsByTagName("contextId");
y = xmlDoc.getElementsByTagName("name");

for (i = 0; i< x.length; i++) {
  var value = x[i].childNodes[0].nodeValue;
  var key = y[i].childNodes[0].nodeValue;
  myHashMap[key] = value;
}

console.log(myHashMap);
Sign up to request clarification or add additional context in comments.

4 Comments

But again if you see my code the value of x and y is getting dynamically increasing but ur code is static, can u give example with reference to my code if possible?
Thanks for quick update,just one more thing like if i want to see the output in console,what shall i do console.log()?
Like what value is added as key and what as a value
Yea, you can add console.log(myHashMap); after the loop to see the result. Alternatively console.log(value); and console.log(key); inside the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.