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.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
// 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

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`.