- DOMParser: parseFromString() method
- Syntax
- Parameters
- Return value
- Examples
- Parsing XML, SVG, and HTML
- Error handling
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- DOMParser
- Constructor
- Instance methods
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- XML Parser
- XML Parser
- Parsing a Text String
- Example
- Example Explained
- The XMLHttpRequest Object
- Example
- Parsing and serializing XML
- Creating an XML document
- Parsing strings into DOM trees
- Parsing URL-addressable resources into DOM trees
- Using XMLHttpRequest
- Serializing an XML document
- Serializing DOM trees to strings
- Serializing HTML documents
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
DOMParser: parseFromString() method
The parseFromString() method of the DOMParser interface parses a string containing either HTML or XML, returning an HTMLDocument or an XMLDocument .
Syntax
parseFromString(string, mimeType)
Parameters
The string to be parsed. It must contain either an HTML, xml, XHTML, or svg document.
A string. This string determines whether the XML parser or the HTML parser is used to parse the string. Valid values are:
- text/html
- text/xml
- application/xml
- application/xhtml+xml
- image/svg+xml
A value of text/html will invoke the HTML parser, and the method will return an HTMLDocument . Any element gets marked non-executable, and the contents of are parsed as markup.
The other valid values ( text/xml , application/xml , application/xhtml+xml , and image/svg+xml ) are functionally equivalent. They all invoke the XML parser, and the method will return a XMLDocument .
Any other value is invalid and will cause a TypeError to be thrown.
Return value
An HTMLDocument or an XMLDocument , depending on the mimeType argument.
Examples
Parsing XML, SVG, and HTML
Note that a MIME type of text/html will invoke the HTML parser, and any other valid MIME type will invoke the XML parser. The application/xml and image/svg+xml MIME types in the example below are functionally identical — the latter does not include any SVG-specific parsing rules. Distinguishing between the two serves only to clarify the code’s intent.
const parser = new DOMParser(); const xmlString = "Beware of the tiger "; const doc1 = parser.parseFromString(xmlString, "application/xml"); // XMLDocument const svgString = ''; const doc2 = parser.parseFromString(svgString, "image/svg+xml"); // XMLDocument const htmlString = "Beware of the leopard"; const doc3 = parser.parseFromString(htmlString, "text/html"); // HTMLDocument console.log(doc1.documentElement.textContent); // "Beware of the tiger" console.log(doc2.firstChild.tagName); // "circle" console.log(doc3.body.firstChild.textContent); // "Beware of the leopard"
Error handling
When using the XML parser with a string that doesn’t represent well-formed XML, the XMLDocument returned by parseFromString will contain a node describing the nature of the parsing error.
const parser = new DOMParser(); const xmlString = "Beware of the missing closing tag"; const doc = parser.parseFromString(xmlString, "application/xml"); const errorNode = doc.querySelector("parsererror"); if (errorNode) // parsing failed > else // parsing succeeded >
Additionally, the parsing error may be reported to the browser’s JavaScript console.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
DOMParser
The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document .
You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.
In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree.
Note that XMLHttpRequest can parse XML and HTML directly from a URL-addressable resource, returning a Document in its response property.
Note: Be aware that block-level elements like
will be automatically closed if another block-level element is nested inside and therefore parsed before the closing
tag.
Constructor
Creates a new DOMParser object.
Instance methods
Parses a string using either the HTML parser or the XML parser, returning an HTMLDocument or XMLDocument .
Examples
The documentation for DOMParser.parseFromString() , this interface’s only method, contains examples for parsing XML, SVG, and HTML strings.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on May 10, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
XML Parser
All major browsers have a built-in XML parser to access and manipulate XML.
XML Parser
The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML.
However, before an XML document can be accessed, it must be loaded into an XML DOM object.
All modern browsers have a built-in XML parser that can convert text into an XML DOM object.
Parsing a Text String
This example parses a text string into an XML DOM object, and extracts the info from it with JavaScript:
Example
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,»text/xml»);
Example Explained
An XML DOM parser is created:
The parser creates a new XML DOM object using the text string:
The XMLHttpRequest Object
The XMLHttpRequest Object has a built in XML Parser.
The responseText property returns the response as a string.
The responseXML property returns the response as an XML DOM object.
If you want to use the response as an XML DOM object, you can use the responseXML property.
Example
Request the file cd_catalog.xml and use the response as an XML DOM object:
xmlDoc = xmlhttp.responseXML;
txt = «»;
x = xmlDoc.getElementsByTagName(«ARTIST»);
for (i = 0; i < x.length; i++) txt += x[i].childNodes[0].nodeValue + "
«;
>
document.getElementById(«demo»).innerHTML = txt;
Parsing and serializing XML
At times, you may need to parse XML content and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we’ll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy.
Serializes DOM trees, converting them into strings containing XML.
Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data.
Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.
A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses.
Creating an XML document
Using one of the following approaches to create an XML document (which is an instance of Document ).
Parsing strings into DOM trees
This example converts an XML fragment in a string into a DOM tree using a DOMParser :
const xmlStr = 'hey!'; const parser = new DOMParser(); const doc = parser.parseFromString(xmlStr, "application/xml"); // print the name of the root element or error message const errorNode = doc.querySelector("parsererror"); if (errorNode) console.log("error while parsing"); > else console.log(doc.documentElement.nodeName); >
Parsing URL-addressable resources into DOM trees
Using XMLHttpRequest
Here is sample code that reads and parses a URL-addressable XML file into a DOM tree:
const xhr = new XMLHttpRequest(); xhr.onload = () => dump(xhr.responseXML.documentElement.nodeName); >; xhr.onerror = () => dump("Error while getting XML."); >; xhr.open("GET", "example.xml"); xhr.responseType = "document"; xhr.send();
The value in the xhr object’s responseXML field is a Document constructed by parsing the XML.
If the document is HTML, the code shown above will return a Document . If the document is XML, the resulting object is actually a XMLDocument . The two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well.
Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is an alias for the Document interface.
Serializing an XML document
Given a Document , you can serialize the document’s DOM tree back into XML using the XMLSerializer.serializeToString() method.
Use the following approaches to serialize the contents of the XML document you created in the previous section.
Serializing DOM trees to strings
First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest .
To serialize the DOM tree doc into XML text, call XMLSerializer.serializeToString() :
const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(doc);
Serializing HTML documents
If the DOM you have is an HTML document, you can serialize using serializeToString() , but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants.
const docInnerHtml = document.documentElement.innerHTML;
As a result, docInnerHtml is a string containing the HTML of the contents of the document; that is, the element’s contents.
You can get HTML corresponding to the and its descendants with this code:
const docOuterHtml = document.documentElement.outerHTML;
See also
Found a content problem with this page?
This page was last modified on Jul 4, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.