XMLSerializer Prints DOM Back As Markup
XMLSerializer turns a DOM document or element back into markup: document form includes the doctype, element form does not; edits serialize as they stand.
Code
// XMLSerializer 把 DOM(含 SVG/XML 文档)序列化回标记文本
const doc = new DOMParser().parseFromString(
'<!DOCTYPE notes><notes><item done="true">ship</item></notes>',
'text/xml',
);
console.log(new XMLSerializer().serializeToString(doc));
// 真实差异点在文档级节点:Document 会把 doctype 一并输出,documentElement 只输出元素本身
// 两种序列化都不带 <?xml …?> 声明——对 Document 同样不加
const root = doc.documentElement;
console.log(new XMLSerializer().serializeToString(root));
// 动态改过的节点同样如实输出:先改再序列化
const item = doc.querySelector('item');
item.setAttribute('done', 'false');
item.textContent = 'draft';
console.log(new XMLSerializer().serializeToString(root));XMLSerializer Prints DOM Back As Markup: reading the source
Demo state sits in top-level bindings: doc, root, item.
What to watch for
- Built on platform APIs alone; no packages to pull in.
Statements that matter
const item = doc.querySelector('item');
item.setAttribute('done', 'false');
const root = doc.documentElement;
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `doc`, `root`, `item`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.