如何使用 JS AJAX 获取 XML 标记的名称

how to get name of a xml tag with js ajax

本文关键字:XML 何使用 JS AJAX 获取      更新时间:2023-09-26

我有一个 xml 文件,我正在用 ajax 拆解:

<country name="UK">
        <person>
            <name>daniel</name>
            <age>25</city>
        </person>
        <person>
            <name>james</name>
            <age>22</city>
        </person>
        <person>
            <name>brandy</name>
            <age>16</city>
        </person>
        <person>
            <name>nathan</name>
            <age>66</city>
        </person>
    </country>
    <country name="france">
        <person>
            <name>paul</name>
            <age>28</city>
        </person>
        <person>
            <name>pierr</name>
            <age>22</city>
        </person>
    </country>

我的任何JS看起来像这样:

<script type="text/javascript">
function loadXMLDoc() {
xmlhttp=null;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() 
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
          xmlDoc=xmlhttp.responseXML;
          var txt="";
          x=xmlDoc.getElementsByTagName("name");
          for (i=0;i<x.length;i++)
            {
            txt=txt + x[i].childNodes[0].nodeValue + "<br />";
            }
          document.getElementById("myDivName").innerHTML=txt;
          //somehow get the country of that person to write here
          document.getElementById("myDivCountry").innerHTML=txt;
          }
      xmlhttp.open("GET","people.xml",true);
      xmlhttp.send();
      }
}
</script>

JS将打印该人的名字,但是我如何获取该人所属国家的名称?

这是为此问题编写的所有示例内容...我没有正确使用 XML - 这是来自我要过滤的另一个位置的提要

谢谢

您可以使用

parentNode属性来访问country标记及其属性名称name以获取其值:

var countryNames = "";
for (var i = 0; i < x.length; i++)
{
    txt += x[i].childNodes[0].nodeValue + "<br />";
    countryNames += x[i].parentNode.parentNode.name + "<br />";
}