1

I know there are loads of examples online, but there is one particularity in my XML which is posing some problems. In fact, I need to loop through my XML and read the Tagname and the text for cars. Issue is that the tag name is different for all elements;

<Vehicles>
   <cars>        
        <Toyota> Test 1 </Toyota>
        <BMW> Test 2 </BMW>
        <VW> Test 3 </VW>
        <Ferrari> Test 4 </Ferrari> 
   </cars> 
</Vehicles> 

What I have here will loop through the Cars but will return only Toyota. How do I read the rest, since the tagnames are all different;

function myFunction(xml) {
  var x, y, z, i, xmlDoc, txt;
  xmlDoc = xml.responseXML;
  txt = "";
  x = xmlDoc.documentElement;     
  y = xmlDoc.getElementsByTagName("cars")[0];
  z = xmlDoc.getElementsByTagName("Toyota");

 // Output 
 for (i = 0; i < z.length; i++) { 
    txt += z[i].childNodes[0].nodeValue + "<br>";
 }
 document.getElementById("main").innerHTML = txt; 
}

Any idea how I can loop through all the children of cars, without having to mention the tag name, and return me both the tagname itself and the text?

1
  • hint: xmlDoc.getElementsByTagName("cars")[0].children is a collection of nodes that are children of cars Commented Aug 24, 2017 at 6:46

2 Answers 2

2

getElementsByTagName('cars')[0] returns a node ... children of nodes are in node.children

let models = Array.from(xmlDoc.getElementsByTagName('cars')[0].children).map(({nodeName:model, textContent:text}) => ({model, text}))

models will be an array of

{ model: "model name", text: "text content of model tag" }
Sign up to request clarification or add additional context in comments.

1 Comment

That's an interesting answer. Thanks mate ;)
1

You can access child node from cars node directly.

try below code, hope this helps

Note: I haven't executed the code, but i hope it will work

    function myFunction(xml) {
   var x, y, z, i, xmlDoc, txt;
  xmlDoc = xml.responseXML;
  txt = "";
  x = xmlDoc.documentElement;     
  y = xmlDoc.getElementsByTagName("cars")[0];

 // Output 
 for (i = 0; i < y.children.length; i++) { 
    txt += y.children[i].nodeName + "<br>";
 }
 document.getElementById("main").innerHTML = txt; 
}

5 Comments

Thanx for your prompt response but it is not working. I'm getting null as output
corrected, i had to use children property instead of childNode
I am having an error with the children.length, saying it is undefined? Anything related to my code or is it the xml file? thnx
recheck your xml, may be in your xml, the first "cars" element has no children
Ok got it.. In fact IE doesn't support children but ChildNodes. Else, its working fine. Many thanks

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.