XML DOM

For accessing and manipulating documents, a standard is defined by the DOM.

“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

For accessing and manipulating HTML documents, the HTML DOM defines a standard way and presents an HTML document as a tree-structure. For accessing and manipulating XML documents, the XML DOM defines a standard way and presents an XML document as a tree-structure. For working with HTML or XML, a good understanding of DOM is necessary.

HTML DOM:

Through the HTML DOM, we can access all the HTML elements.

Example:

<!DOCTYPE html>
<html>
<body>
 
<h1 id="demo">Hello World!</h1>
 
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'See You Again!'">Click
</button>
 
</body>
</html>

Output 1:

Output 2:

Explanation:

In the above example, the value of an HTML element changes with id=”demo”.

XML DOM:

How to get, change, add, and delete XML elements is defined by the XML DOM as a standard. Through the XML DOM, we can access all the XML elements.

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>
    <author>Author 4</author>
    <year>2004</year>
    <price>350.00</price>
  </book>
 
</bookstore>

Example:

<!DOCTYPE html>
<html>
<body>
 
<p id="demo"></p>
 
<script>
var parser, xmlDoc;
var text = "<bookstore><book>" +
"<title>ABC</title>" +
"<author>Author Name</author>" +
"<price>100.00</price>" +
"</book></bookstore>";
 
 
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
 
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
 
</body>
</html>

Output:

Explanation:

In the above example, we are loading a text string into an XML DOM object. We then extract the info from it with JavaScript. The below line of code retrieves the text value of the first <title> element in an XML document:

txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Please Share