简体   繁体   English

当XML内容作为XML文件接收时,使用Ajax和Javascript加载XML数据

[英]Load XML data using Ajax and Javascript when XML content is received as XML file

I'm trying to display data from the xml file by first getting the content of the xml file and storing it in XML DOM. 我试图通过首先获取xml文件的内容并将其存储在XML DOM中来显示xml文件中的数据。 Once the DOM object is created it is then parsed. 创建DOM对象后,便会对其进行解析。 I used a for loop so as to get data from each child node of the parent node but somehow only the second node's data is showing. 我使用了for循环,以便从父节点的每个子节点获取数据,但是不知何故,仅显示了第二个节点的数据。

This is the code where the error is: 这是错误所在的代码:

    xmlhttp.open("GET","company.xml", false); //sets the request for calling company.xml
    xmlhttp.send(); //sends the request

    xmlDoc = xmlhttp.responseXML; //sets and returns the content as XML DOM

    //parsing the DOM object

    var employeeCount = xmlDoc.getElementsByTagName("Employee");

    for(i=0; i<employeeCount.length; i++)
    {
        document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
        document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
        document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
    }

The XML file: XML文件:

<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
    <Nickname>Tania</Nickname>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>

This the output: 这样的输出:

在此处输入图片说明

How can i display the data from node [0] as well? 如何显示节点[0]中的数据? Any suggestions will be appreciated. 任何建议将不胜感激。 Thanks. 谢谢。

The problem is that you're overwriting data from previous Employee on every iteration : 问题是您每次迭代都会覆盖前一个Employee数据:

for(i=0; i<employeeCount.length; i++)
{
    document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
    document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
    document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}

That's why only the last Employee data remains in innerHTML s in the end. 这就是为什么最后只有Employee数据最后保留在innerHTML中的原因。

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

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