Reading XML documents with DOMParser
While XMLHttpRequest
allows us to both download and parse XML documents, sometimes we might want to parse XML data documents manually. For example, manual parsing would enable us to include arbitrary XML data (for example, XML-based templates) inside the page in a script
tag. This can help to reduce the number of requests sent to the browser.
In this recipe, we are going to read a simple XML document from a textarea
input and parse it using DOMParser
, and then display the result as a tree.
How to do it...
Let's write the test HTML page and the parser:
Create
index.html
, it should contain atextarea
element to input XML (a sample XML document is included), a placeholder for the documentbody
object, and some CSS styles for the document tree:<!DOCTYPE HTML> <html> <head> <title>Deserializing XML with DOMParser</title> <style type="text/css"> div.children { padding-left: 3em; } h3 { padding:0; margin:0; } .children .text ...