Seeking Knowledge
Seeking Knowledge

Reputation: 162

Access an XML value using jQuery

I have this XML

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<sizeResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<sizeReturn xsi:type="xsd:int">1</sizeReturn>
</sizeResponse>
</soapenv:Body>
</soapenv:Envelope>

I want to access the 1 but .find() is not working it's giving me this error in my console

Uncaught TypeError: Object <?xml version="1.0"
encoding="UTF-8"?><soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn
xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope>
 has no method 'getElementsByTagName'

How can I access it otherwise using jQuery or JS (if there's a way using an Xpath plugin please provide the Xpath expression) ?

Thank you

Upvotes: 0

Views: 309

Answers (2)

Nithin Paul
Nithin Paul

Reputation: 2199

Can you try this one.

<script>
    function GetVal()
    {
        var txt = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse   soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn   xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope>';
        if (window.DOMParser)
        {
            parser=new DOMParser();

            xmlDoc = parser.parseFromString(txt, "text/xml");

            var v = xmlDoc.getElementsByTagName("sizeReturn")[0].childNodes[0].nodeValue;
            alert("t" +v);
        }
        else // Internet Explorer
        {
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async=false;
            xmlDoc.loadXML(txt); 
        }
    }

</script>

Cheers :)

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this:

var xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse   soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn   xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
console.log($xml.find("sizeReturn").html());

Read Docs http://api.jquery.com/jQuery.parseXML/

Fiddle: http://jsfiddle.net/cY5xZ/

Upvotes: 1

Related Questions