XML DOM (Document Object Model) is a way to represent and interact with XML documents as a tree of objects. Nodes are the fundamental components of this tree structure. Here's a simple explanation of creating nodes in XML DOM with an example:
XML DOM defines several types of nodes, but the main ones you typically work with are:
<book>
, <title>
, <author>
, etc.id="001"
.<title>Harry Potter</title>
.<!-- This is a comment -->
.Let's create a simple XML structure using XML DOM in JavaScript (since JavaScript is commonly used for DOM manipulation):
Example
// Creating an XML document var xmlDoc = document.implementation.createDocument("", "books", null); // Creating an element node var bookNode = xmlDoc.createElement("book"); // Creating a text node var titleNode = xmlDoc.createElement("title"); var titleText = xmlDoc.createTextNode("Harry Potter"); titleNode.appendChild(titleText); // Creating another element node var authorNode = xmlDoc.createElement("author"); var authorText = xmlDoc.createTextNode("J.K. Rowling"); authorNode.appendChild(authorText); // Appending elements to the book node bookNode.appendChild(titleNode); bookNode.appendChild(authorNode); // Appending book node to the XML document xmlDoc.documentElement.appendChild(bookNode); // Serializing the XML document to a string for demonstration var xmlString = new XMLSerializer().serializeToString(xmlDoc); console.log(xmlString);
In this example:
document.implementation.createDocument("", "books", null)
.<book>
using xmlDoc.createElement("book")
.<title>
and <author>
, and append them to their respective element nodes.<title>
and <author>
nodes to the <book>
node.<book>
node to the root element of the XML document (xmlDoc.documentElement
).The serialized XML string (xmlString
) after running the above code will look like this:
Example
<?xml version="1.0"?> <books> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> </book> </books>
This demonstrates how to create nodes in an XML DOM representation using JavaScript. Each node (element, text, etc.) is created using methods provided by the XML DOM API, and then appended to build up the structure of the XML document.