如何在javascript中循环XML节点?

时间:2022-12-31 14:11:44

I try to loop through XML nodes that consist of users to create en html table on my website

我尝试循环遍历由用户组成的XML节点,以在我的网站上创建en html表

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);
}

the xml look like this

xml看起来像这样

<websites_name>
<user>...</user>
<user>...</user>
.
.
.
</websites_name>

UPDATE

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);
}

1 个解决方案

#1


13  

One of the least intuitive things about parsing XML is that the text inside the element tags is actually a node you have to traverse into.

解析XML最不直观的一点是,元素标记内的文本实际上是您必须遍历的节点。

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:

假设它是 文本数据 ,您不仅需要遍历用户元素的文本节点来提取文本数据,而且还必须在DOM中创建一个包含该数据的文本节点才能看到它。请参见nodeValue和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);
}   

#1


13  

One of the least intuitive things about parsing XML is that the text inside the element tags is actually a node you have to traverse into.

解析XML最不直观的一点是,元素标记内的文本实际上是您必须遍历的节点。

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:

假设它是 文本数据 ,您不仅需要遍历用户元素的文本节点来提取文本数据,而且还必须在DOM中创建一个包含该数据的文本节点才能看到它。请参见nodeValue和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);
}