Parse content like XML, with jQuery

2020-02-14 19:54发布

I have this content from one input value:

var xml_url  = $("input").val();
alert(xml_url);

Output:

<trans>
    <result>
        <item1>1</item1>
        <item2>content</item2>
        <item3>NA</item3>
        <item4>0</item1>
    </result>
</trans>

The structure is as a XML file. I want to get this data.

I have this code:

<script language="javascript">
    $(document).ready(function(){
        var xml_url  = $("input").val();
          $(xml_url).find("result").each(function()  
          {         
            alert($(this).find("item3').").text());
          });
    });
</script>

It works fine in firefox, but not in IE7/8.

Any suggestions? Thanks a lot.

1条回答
Emotional °昔
2楼-- · 2020-02-14 20:22

Never rely on jQuery for parsing XML.

See

Use a proper parser to do the job, and then use jQuery to find the desired nodes. The example you gave works on Firefox, but not on Chrome, Safari or IE. The function below will construct a XML document from a string.

function parseXML(text) {
    var doc;

    if(window.DOMParser) {
        var parser = new DOMParser();
        doc = parser.parseFromString(text, "text/xml");
    }
    else if(window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = "false";
        doc.loadXML(text);
    }
    else {
        throw new Error("Cannot parse XML");
    }

    return doc;
}

Use as:

// Parse and construct a Document object
var xml = parseXML(xml_url);

// Use jQuery on the object now
$(xml).find("result").each(function()  
{
    alert($(this).find("item3").text());
});
查看更多
登录 后发表回答