Aakash Doshi
Aakash Doshi

Reputation: 202

extract value from xml using pure javascript

i am receiving xml as a web response.

<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">
<s:Header/>
    <s:Body>
        <ProductIdResponse xmlns="http://example.org/">
            <Product>123</Product>
        <ProductIdResponse>
    </s:Body>
</s:Envelope>

I am looking to extract value from xml using pure javascript and store it in variable. there are many example in stackoverflow but all are using DOM elements and jquery.

any help would be appreciated.

Upvotes: 0

Views: 1745

Answers (1)

Banana
Banana

Reputation: 7473

have a look here: XML Parser

you load the xml into an xml document, and then access the elements the same way you would on your page's document:

    //initialize your xml for testing purposes
    txt='<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
    txt=txt+'<s:Header/>';
    txt=txt+'<s:Body>';
    txt=txt+'<ProductIdResponse xmlns="http://example.org/">';
    txt=txt+' <Product>123</Product>';
    txt=txt+'<ProductIdResponse>';
    txt=txt+'</s:Body>';
    txt=txt+'</s:Envelope>';
    
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(txt, "text/xml");
    } else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(txt);
    }
    var myProduct = xmlDoc.getElementsByTagName("Product")[0].innerHTML;
    alert(myProduct);

If you dont want to parse the xml into DOM, you can alternatively retrieve the data using RegEx matching

check Here for a good RegEx tester where you can practice regex.

//initialize your xml for testing purposes
txt = '<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
txt = txt + '<s:Header/>';
txt = txt + '<s:Body>';
txt = txt + '<ProductIdResponse xmlns="http://example.org/">';
txt = txt + ' <Product>123</Product>';
txt = txt + ' <Product>Product 2</Product>';
txt = txt + '<ProductIdResponse>';
txt = txt + '</s:Body>';
txt = txt + '</s:Envelope>';

var myProducts = txt.match(/<Product>(.*?)<\/Product>/g);
myProducts.forEach(function(val, id) {
  myProducts[id] = myProducts[id].replace(/(<([^>]+)>)/ig, "");
});
console.log(myProducts);
alert("2nd product is: " + myProducts[1]);

Upvotes: 3

Related Questions