简体   繁体   English

我如何在 JavaScript 中循环遍历 XML 节点?

[英]How do I loop through XML nodes in JavaScript?

I'm trying to loop through XML nodes containing information about users to create an HTML table on my website.我正在尝试遍历包含用户信息的 XML 节点,以在我的网站上创建一个 HTML 表格。

This is what the XML looks like:这是 XML 的样子:

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

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.在 JavaScript 中解析 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.假设它是<user>text data</user> ,您不仅需要遍历用户元素的文本节点来提取文本数据,还必须在 DOM 中创建一个包含该数据的文本节点才能看到它。 See nodeValue and and createtextnode :请参阅nodeValuecreatetextnode

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM