[英]extract value from xml using pure javascript
我正在接收xml作為網絡響應。
<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>
我正在尋找使用純JavaScript從xml提取值並將其存儲在變量中。 在stackoverflow中有很多示例,但是都使用DOM元素和jquery。
任何幫助,將不勝感激。
在這里看看: XML Parser
您將xml加載到xml文檔中,然后以與在頁面文檔中相同的方式訪問元素:
//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);
如果您不想將xml解析為DOM,則可以使用RegEx匹配來檢索數據。
在這里查看一個好的RegEx測試儀,您可以在其中練習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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.