bhylu.com

Advertisements

XML DOM Serialization

XMLSerializer converts a DOM tree to XML source. Reparse the result to check that your exported structure still has the intended names and values.

How it works

Serialization is useful for downloads, previews and request bodies, but it is not a schema validator. The output may use different namespace prefixes or empty-element spellings while representing the same tree. Set text through DOM APIs so special characters are escaped correctly. A byte-level signature requires a defined canonicalization and signing process, not a simple comparison of two serializer results.

Run the code

Save this complete HTML source as index.html and open it in a normal browser. Select Run example to execute it. The document embeds its XML and runs without a network connection. Browser DOM/XPath examples do not run in the XML syntax playground.

Download the complete dom-serialize.html source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.

Example

dom-serialize.html

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Seed exchange XML lab</title><style>body{font:18px/1.6 system-ui;margin:24px;color:#0f3464}pre{white-space:pre-wrap;overflow-wrap:anywhere}button{font:inherit}main{max-width:55rem;margin:auto}</style></head>
<body><main><h1>Seed exchange XML lab</h1><button id="run" type="button">Run example</button><pre id="result" aria-live="polite"></pre></main>
<script>
document.querySelector('#run').addEventListener('click', async () => {
  const show = value => document.querySelector('#result').textContent = String(value);
  const parse = text => {
    if (/<!\s*(DOCTYPE|ENTITY)/i.test(text)) throw new Error('Declarations disabled');
    const doc = new DOMParser().parseFromString(text, 'application/xml');
    if (doc.querySelector('parsererror')) throw new Error('Malformed XML');
    return doc;
  };
  const doc = parse("<exchange region=\"west\">\n  <packet id=\"p1\" available=\"true\"><name>Marigold</name><quantity>12</quantity><category>flower</category></packet>\n  <packet id=\"p2\" available=\"false\"><name>Fenugreek</name><quantity>0</quantity><category>herb</category></packet>\n  <packet id=\"p3\" available=\"true\"><name>Basil</name><quantity>7</quantity><category>herb</category></packet>\n</exchange>");
  try {
    doc.querySelector('name').textContent = 'Peas & beans';
    const source = new XMLSerializer().serializeToString(doc);
    const again = parse(source);
    show(source.includes('&amp;') + ' / ' + again.querySelector('name').textContent);
  } catch (error) { show('Error: ' + error.message); }
});
</script></body></html>

Expected result

true / Peas & beans

The source includes an escaped ampersand; the reparsed field contains the ordinary character. The round trip preserves the relevant text meaning. An application should also check its required fields and validation contract after editing.

Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.