如何在 JavaScript 中遍历 XML 节点? [英] How do I loop through XML nodes in JavaScript?

查看:81
本文介绍了如何在 JavaScript 中遍历 XML 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历包含用户信息的 XML 节点,以在我的网站上创建 HTML 表格.

I'm trying to loop through XML nodes containing information about users to create an HTML table on my website.

这是 XML 的样子:

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

更新

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

推荐答案

在 JavaScript 中解析 XML 最不直观的事情之一是元素标签内的文本实际上是您必须遍历的节点.

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.

假设是<user>text data</user>,你不仅要遍历user元素的text节点来提取你的文本数据,还要创建一个text在 DOM 中使用该数据的节点来查看它.请参阅 nodeValuecreatetextnode:

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

这篇关于如何在 JavaScript 中遍历 XML 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆