Convert HTML to XML in JavaScript by parsing the source with DOMParser in HTML mode and serializing the parsed document with XMLSerializer. The result represents the browser's parsed DOM, so it is not a byte-for-byte copy of the original HTML.
That distinction matters when the source contains malformed tags, mixed-case names, entities, scripts, styles, or whitespace. The browser workflow below turns interpreted HTML into XML text, checks that text as XML, and shows where an exact HTML-to-JavaScript string belongs in the process.

Convert an HTML string to XML in JavaScript
Use this browser-based sequence for a complete document or a fragment.
Keep the source in an ordinary JavaScript string named htmlSource. Load it as text and avoid auto-formatting it before conversion.
Parse it with DOMParser in HTML mode: const htmlDoc = new DOMParser().parseFromString(htmlSource, "text/html");
Choose the output scope. Use htmlDoc for the complete parsed document, including its represented structure, or use htmlDoc.body when the consumer needs only the body element.
Serialize the chosen node: const xmlText = new XMLSerializer().serializeToString(htmlDoc); For a body fragment, pass htmlDoc.body instead. This produces XML text from the DOM rather than rewriting the original source string.
Check the result as XML: const xmlDoc = new DOMParser().parseFromString(xmlText, "application/xml"); if (xmlDoc.querySelector("parsererror")) throw new Error("Invalid XML");
Use xmlText only after that check passes. If the consumer requires an XML declaration, prepend <?xml version="1.0" encoding="UTF-8"?> and save the result as UTF-8.
Use text/html, not application/xml, for ordinary HTML because HTML accepts syntax that XML rejects. The application/xhtml+xml mode is appropriate only when the source is already XML-compatible XHTML. This workflow targets browsers; in Node.js, use maintained parsing and serialization packages when these browser globals are unavailable.
What changes during the conversion
HTML and XML have different grammars, so converting a source string necessarily involves interpretation unless you only serialize it as text.
The HTML parser can add implied document elements and place content into head or body according to HTML rules.
Standard HTML element and attribute names may be lowercased, while XML names remain case-sensitive.
Unclosed or misnested tags may be repaired in the DOM instead of being reported as fatal errors.
Named HTML entities can be decoded and then represented differently by the XML serializer.
XMLSerializer expresses the DOM in XML form, which can include self-closing empty elements and namespace declarations.
Therefore, “valid XML” and “identical to the submitted HTML” are separate requirements. If the downstream schema requires particular element names, attributes, namespaces, or a single root, add an explicit transformation with a maintained parser instead of assuming serialization enforces those rules.
Choose the right conversion workflow
Choose a workflow based on what “convert” means in your application:
| Approach | Output | Original source | Best use |
|---|---|---|---|
| DOMParser plus XMLSerializer | An XML serialization of the parsed HTML DOM | May change because parser rules apply | You need XML text representing the browser's interpretation of the HTML |
| HTML-to-JavaScript string serialization | One JavaScript const assignment containing the supplied text | Preserved at the string-literal level | You need to embed or transport exact HTML before a separate parse |
| Maintained parser plus explicit mapping | XML nodes and attributes defined by your rules | Depends on the mapping | You need strict schemas, namespace rules, renaming, or business validation |
If “convert” means putting an HTML fragment into an XML text node rather than changing its structure, escape it as XML text instead. Ampersands and less-than signs must be escaped; quotation marks need escaping only when they appear in an XML attribute value. This is a different operation from DOMParser plus XMLSerializer.
Check namespaces and embedded content
Run a final review against the XML consumer, not only the HTML source.
Inspect the root element and namespace declarations. A full HTML document may carry the XHTML namespace, while embedded SVG or MathML can introduce additional namespace considerations.
Review script, style, template, and other raw-text content. Their HTML parsing rules are special, and the serialized result still needs an XML parse check.
Check meaningful whitespace in preformatted areas and confirm that entity differences do not affect the consumer.
Validate against the destination's schema or contract when well-formed XML is not enough. A browser XML parser checks syntax; it does not enforce an application schema.
Keep the original source alongside the generated XML when debugging. Comparing them can reveal whether a difference came from HTML parsing, entity handling, case normalization, or the selected output scope.
Preserve HTML as a JavaScript string
If the source must be embedded in JavaScript before the DOM conversion, use the HTML to JavaScript Converter for an exact-text serialization step. It does not create XML; it creates a copy-ready JavaScript const assignment that your XML workflow can consume afterward.
Paste the HTML source exactly as it should appear in the final string. The converter accepts a fragment or full document; do not clean, format, or repair the source first when exact preservation is the goal.
Enter a non-reserved ASCII JavaScript variable name. Accepted portable names begin with a letter, underscore, or dollar sign, while reserved words such as class, const, for, and return are rejected. Unicode identifiers are outside this conservative input set.
Choose double quotes, single quotes, or a template literal, then convert. The output always uses const; change that declaration manually only when the application truly requires reassignment or a different module pattern.
Copy the assignment, run it in an isolated test, and assert that the resulting string exactly equals the original input before integration.
The converter protects the selected delimiter, backslashes, control characters, and line terminators. Double-quote mode escapes literal double quotes while leaving apostrophes readable; single-quote mode does the reverse. Backslashes are escaped so Windows paths, regular-expression text, and existing escape sequences retain their literal characters after JavaScript evaluates the assignment. These rules follow the ECMAScript string-literal grammar.
Template literals allow readable multiline source, but an unescaped backtick closes the literal and ${ starts expression interpolation. The converter escapes both so pasted HTML remains literal text. The MDN template-literal reference explains the underlying delimiter and interpolation rules.
Everything runs in the current browser tab. The HTML is not uploaded, stored, executed, previewed, or sent to a server, and no account or dependency is required. Because this is text serialization rather than parsing, tags, attributes, whitespace, comments, entities, inline styles, and malformed markup remain text. The tool does not build a DOM, reorder attributes, normalize case, repair unclosed tags, or turn HTML into JSX.
Integrate the result without creating a security risk
The generated assignment is source code, and neither XML text nor a valid JavaScript literal is automatically safe to insert into a page.
Never use eval or new Function merely to display HTML.
Prefer textContent when the destination does not require markup.
When rendering untrusted markup is unavoidable, use a maintained sanitizer and a restrictive Content Security Policy.
If the string is later assigned to innerHTML, passed to a template engine, evaluated as code, or combined with untrusted data, apply escaping and security controls appropriate to that destination.
Treat conversion as data preparation, not validation or sanitization. If XML is later embedded in another XML document as text, escape it for that destination instead of treating the serialized markup as an already-safe child element.
Related reading: JavaScript Playground: Command Line vs Online.
Related reading: JavaScript Keycodes API Alternative: Inspect Browser Events.