Parse content like XML using jQuery

I have this content with one input value:

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

Conclusion:

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

The structure is an 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? Many thanks.

+2
source share
1 answer

Never rely on jQuery for XML parsing.

Cm

Use the appropriate parser to complete the job, and then use jQuery to find the nodes you need. An example that you gave in Firefox, but not in Chrome, Safari or IE. The following function will build an 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());
});
+2
source

All Articles