I'm trying to loop through XML nodes containing information about users to create an HTML table on my website.
This is what the XML looks like:
<websites_name>
<user>...</user>
<user>...</user>
.
.
.
</websites_name>
And this is the code I'm trying to parse it with:
for(var user in xmlhttp.getElementsByTagName('user')){ //fix this row to me
//Create a new row for tbody
var tr = document.createElement('tr');
document.getElementById('tbody').appendChild(tr);
}
UPDATE
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","some URL",true);
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var root = xmlDoc.getElementsByTagName('websites_name');
for(var i=0, i<root[0].childNodes.length,i++){
//Create a new row for tbody
var tr = document.createElement('tr');
document.getElementById('tbody').appendChild(tr);
}
Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.
A Schema describes the elements and attributes that are valid in an XML document, and the contexts in which they are valid.
One of the least intuitive things about parsing XML in JavaScript is that the text inside the element tags is actually a node you have to traverse into.
Assuming it's <user>text data</user>
, you not only have to traverse into the text node of the user element to extract your text data, but you have to create a text node with that data in the DOM to see it. See nodeValue and and createtextnode:
// get XML
var xml = xhr.responseXML;
// get users
var users = xml.getElementsByTagName("user");
for (var i = 0; i < users.length; i++) {
var user = users[i].firstChild.nodeValue;
var tr = document.createElement("tr");
var td = document.createElement("td");
var textNode = document.createTextNode(user);
td.appendChild(textNode);
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With