Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing XML

XML DOM Create Nodes:



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:

Nodes in XML DOM:

XML DOM defines several types of nodes, but the main ones you typically work with are:

  1. Element nodes: Represent elements like <book>, <title>, <author>, etc.
  2. Attribute nodes: Represent attributes of elements, like id="001".
  3. Text nodes: Represent text content within elements, such as "Harry Potter" within <title>Harry Potter</title>.
  4. Comment nodes: Represent comments in XML, like <!-- This is a comment -->.

Example of Creating Nodes:

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);

Explanation:

In this example:

Output:

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.




Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java