如何循环浏览 javascript 中的 XML 节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4362392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:05:28  来源:igfitidea点击:

How do I loop through a XML nodes in javascript?

javascriptxml

提问by einstein

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

更新

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

回答by P. Myer Nore

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 nodeValueand and createtextnode:

假设它是<user>text data</user>,您不仅必须遍历用户元素的文本节点来提取文本数据,而且还必须在 DOM 中使用该数据创建一个文本节点才能查看它。请参阅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);
}