简体   繁体   English

使用JQUERY / AJAX遍历XML文件

[英]iterate through XML file using JQUERY / AJAX

I have a code like this: 我有这样的代码:

    <!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

<p id="demo"></p>

<script>

    var x, i ,xmlDoc;
    var txt = "";
    var text = "";

    $.ajax({
        type: "GET" ,
        url: "data.xml" ,
        dataType: "xml" ,
        success: function(xml) {

            //  xmlDoc = $.parseXML(xml);

            $(xml).find('object').each(function(){
                console.log($(this).text());
                console.log($(this).nodeName);
            });
        }
    });


    document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>    

This spits out the values of the fields, however how do I get the names of the XML nodes as well? 这会吐出字段的值,但是如何获取XML节点的名称呢? So in a file like: 所以在一个像这样的文件中:

   <root>
<item>hello</item>
</root>

I only get "hello" 我只会收到“你好”

I need something like "item" and "hello" 我需要“项目”和“你好”之类的东西

is it possible, if so, how? 如果可能,怎么可能? thanks! 谢谢!

With the sample XML, I have shown this sample. 使用样本XML,我已经显示了此样本。 You can replace them with the dynamic XML. 您可以将它们替换为动态XML。

 var x, i ,xmlDoc; var txt = ""; var text = ""; // Replace with your dynamic xml var text = "<root>"+ "<item>hello</item>"+ "</root>"; var parser = new DOMParser(); var xmlDoc = parser.parseFromString(text,"text/xml"); // documentElement always represents the root node x = xmlDoc.documentElement.childNodes; for (i = 0; i < x.length ;i++) { console.log("Node :",x[i].nodeName); console.log("Value :",x[i].childNodes[0].nodeValue); txt += x[i].nodeName + ": " + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("xmlData").innerHTML = txt; 
 <div id="xmlData"></div> 

Source : https://www.w3schools.com/xml/tryit.asp?filename=try_dom_parsertest3 来源: https : //www.w3schools.com/xml/tryit.asp?filename=try_dom_parsertest3

You are looking for an object tag which is not present in the xml response. 您正在寻找xml响应中不存在的object标签。 (Also since you are using the datatype: 'xml' JQuery will return an XMLElement). (此外,由于您使用的是datatype: 'xml' JQuery将返回XMLElement)。 Instead look for the item tags and then you can access the nodeName & textContent properties. 而是查找item标签,然后可以访问nodeNametextContent属性。

https://jsfiddle.net/zms0qwa1/ https://jsfiddle.net/zms0qwa1/

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

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