0

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.

0

1 Answer 1

3

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]);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for reply. But I am not looking for DOM :(
@user2202257 What do you expect to use if not DOM? What's wrong with using a DOM?
@user2202257 You are confusing HTML and jQuery with DOM. DOM is a standard for XML representation and manipulation of documents. So you are looking for DOM. You should use DOMParser as described in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.