Parsing complex XML with jQuery

2019-08-06 12:25发布

I'm trying to parse the following XML with the following jQuery. Nothing is displayed on the page. I know it's getting the file. I've looked online and though there are many examples of parsing xml with jquery none of them looked like this formatting.

XML:

<?xml version="1.0" encoding="utf-8"?>
<wcm:root xmlns:wcm="http://www.stellant.com/wcm-data/ns/8.0.0" version="8.0.0.0">

    <wcm:element name="title"></wcm:element>
    <wcm:element name="wide_image">&lt;img src=&#39;[!--$wcmUrl&amp;amp;x28;&#39;resource&amp;#39;,&amp;#39;CMS3_130980&amp;#39;&amp;amp;x29;--]&amp;#39;/&gt;</wcm:element>
    <wcm:element name="image">&lt;img src="[!--$wcmUrl('resource','CMS3_132821')--]"/&gt;</wcm:element>
    <wcm:element name="body">&lt;p&gt;
        Paragraph of text goes here.&lt;br /&gt;&lt;br /&gt;
        Paragraph of text goes here.&lt;br /&gt;&lt;br /&gt;
        Paragraph of text goes here.&lt;br /&gt;&lt;br /&gt;
        Paragraph of text goes here.&lt;br /&gt;&lt;br /&gt;
        Paragraph of text goes here.&lt;/p&gt;
</wcm:element>
</wcm:root>

HTML & jQuery:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "link_to_my_file.xml",
        dataType: "xml",
        success: parseXml
    });
});

function parseXml(xml){
    $(xml).find("wcm\\3a root").each(function(){
    alert("Test");
        $("#output").append($(this).attr("title") + "<br />");
        $("#output").append($(this).attr("wide_image") + "<br />");
        $("#output").append($(this).attr("image") + "<br />");
        $("#output").append($(this).attr("body") + "<br />");
        });
     };

</script>

<div id="output"></div>

</html>

1条回答
Animai°情兽
2楼-- · 2019-08-06 12:57

You have to escape the : in the selector: http://mothereff.in/css-escapes#1wcm%3Aroot

So, instead of:

$(xml).find("wcm:root")

Use:

$(xml).find("wcm\\3a root")

Also, your code snippet is invalid JavaScript (missing } after the parseXml function declaration). Check your error console.

查看更多
登录 后发表回答