Introduction to the XML Document Object Model (DOM)
The greatest attribute that XML contributes to any Web Development project is being processed and stored as plain text. This means all web browsers have a built-in XML DOM. We will learn more about the XML DOM in the next post. You can find additional information on Microsft Learn. Today we will explore how to parse data into an XML Document.
Parsing Data into XML DOM object
The XML Parser stores data in memory. For example, I will store my truck from the button as an XML DOM object. To understand exactly what's happening, let's look at a simple request for my car.
The XML string to be parsed:
const xmlData = `
<dealership> <car id="1" type="truck"> <make>Toyota</make> <model>Tacoma</model> <year>1987</year> <owner> <name>Chris</name> <address> <street>12 ST</street> <city>Somewhere</city> <state>MT</state> <zip>12322</zip> </address> </owner> </car> </dealership>`;
// Create a new DOMParser instance:
parser = new DOMParser();
// Parse the XML string into an XML document:
xmlDoc = parser.parseFromString(text, "text/xml");
// Extract the text value of the first <owner> element and set it as the innerHTML of the paragraph element with id “car_owner”:
document.getElementById("car_owner").innerHTML = xmlDoc.getElementsByTagName("owner")[0].childNodes[0].nodeValue;