I am trying to parse a text to a text/xml and get the value that is inside a child Node but is giving this error to me (Cannot read properties of undefined (reading 'childNodes'). I want the value true inside of the GetValidUserPasswordResult. This is the code that i am making:
var text = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetValidUserPasswordResponse xmlns="http://microsoft.com/webservices/"><GetValidUserPasswordResult>true</GetValidUserPasswordResult></GetValidUserPasswordResponse></soap:Body></soap:Envelope>';
console.log(text);
parser = new DomParser();
xmlDoc = parser.parseFromString(text, "text/xml");
xmlDoc1 = xmlDoc.getElementsByName("GetValidUserPasswordResult")[0].childNodes[0].text;
console.log(xmlDoc1)
CodePudding user response:
I already found the answer, i was doing on node.js but the implementation of DOMParser on node is xmldom, so the result was this one
var DOMParser = require('xmldom').DOMParser; var parser = new DOMParser(); var document = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetValidUserPasswordResponse xmlns="http://microsoft.com/webservices/"><GetValidUserPasswordResult>true</GetValidUserPasswordResult></GetValidUserPasswordResponse></soap:Body></soap:Envelope>', 'text/xml'); var xmlDoc1 = document.getElementsByTagName("GetValidUserPasswordResult")[0].childNodes[0].nodeValue; console.log(xmlDoc1)
CodePudding user response:
I tried to reprouduce your issue and made some changes in it. Hope that's how you wanted it to work.
var text = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetValidUserPasswordResponse xmlns="http://microsoft.com/webservices/"><GetValidUserPasswordResult>true</GetValidUserPasswordResult></GetValidUserPasswordResponse></soap:Body></soap:Envelope>';
parser = (new DOMParser());
xmlDoc = parser.parseFromString(text, "text/xml");
xmlDoc1 =xmlDoc.children[0].childNodes[0].children[0].tagName
console.log(xmlDoc1)
You can see the working example here - https://jsfiddle.net/h2apkmj7/1/