'DOMParser Typescript- Parsing HTML
I'm running into some trouble with the DOMParser. I'm using intelliJ IDE and writing in Typescript.
Here is my code:
public domparser = new DOMParser();
this.domdoc = this.domparser.parseFromString(this.xmlDoc, 'text/xml');
console.log("domdoc: " + this.domdoc);
I'm seeing
domdoc: [object XMLDocument] in my console.
Any suggestions on how to print the XML document, rather than just '[object XMLDocument]'?
Thank you.
Solution 1:[1]
You can use the querySelector and the wildcard * to select all the xml element.
public domparser = new DOMParser();
this.domdoc = this.domparser.parseFromString(this.xmlDoc, 'text/xml');
let elements = this.domdoc.querySelectorAll("*");
for (element of elements){
console.log(element.innerHTML);
}
Solution 2:[2]
console.log("domdoc: " + this.domdoc); this line need some changes. Please remove the string "domdoc:" appended with the object.
Final code looks like:
public domparser = new DOMParser();
this.domdoc = this.domparser.parseFromString(this.xmlDoc, 'text/xml');
console.log(this.domdoc);
Solution 3:[3]
For loop like the first answer cannot be used in Angular 11.
This can't be used
for (element of elements){
}
This can be used
let parsedXMLResponse = (new DOMParser()).parseFromString("some string value", "text/xml");
let result = parsedXMLResponse.getElementsByTagName("<name of tag>");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Anoop Sankar |
| Solution 3 | Dave Lee |
