Dom Nodes in XML
DOM Nodes in XML
In the XML Document Object Model (DOM), everything in an XML document is represented as a node. Each node corresponds to a part of the XML structure.
Types of DOM Nodes in XML
| Node Type | Description | nodeType Value |
|---|---|---|
| Document Node | Represents the entire XML document | 9 |
| Element Node | Represents an XML element (tag) | 1 |
| Attribute Node | Represents an attribute on an element | 2 |
| Text Node | Represents the text inside an element | 3 |
| CDATA Section Node | Represents CDATA sections | 4 |
| Comment Node | Represents comments in XML | 8 |
| Processing Instruction Node | Represents processing instructions | 7 |
Node Relationships
Parent Node — node that contains the current node
Child Nodes — nodes contained inside a node
Sibling Nodes — nodes with the same parent
Example XML
<book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> <!-- This is a comment --> <![CDATA[Some <CDATA> content]]></book>Representation of Nodes
| Node Type | Example in XML |
|---|---|
| Document Node | The whole XML document |
| Element Node | <book>, <title>, <author> |
| Attribute Node | id="101" |
| Text Node | Text inside <title> and <author> |
| Comment Node | <!-- This is a comment --> |
| CDATA Section Node | <![CDATA[Some <CDATA> content]]> |
Accessing Nodes in JavaScript
const parser = new DOMParser();const xmlString = ` <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> <!-- This is a comment --> <![CDATA[Some <CDATA> content]]> </book>`;const xmlDoc = parser.parseFromString(xmlString, "text/xml");// Document nodeconsole.log(xmlDoc.nodeType); // 9// Element node (<book>)const book = xmlDoc.getElementsByTagName("book")[0];console.log(book.nodeType); // 1console.log(book.nodeName); // "book"// Attribute nodeconst idAttr = book.getAttributeNode("id");console.log(idAttr.nodeType); // 2console.log(idAttr.nodeName); // "id"console.log(idAttr.nodeValue); // "101"// Text node (<title> text)const title = book.getElementsByTagName("title")[0];const titleText = title.firstChild; // Text nodeconsole.log(titleText.nodeType); // 3console.log(titleText.nodeValue); // "Effective Java"// Comment nodeconst commentNode = book.childNodes[3]; // Could vary due to whitespace text nodesif (commentNode.nodeType === 8) { console.log("Comment: " + commentNode.nodeValue);}// CDATA section nodeconst cdataNode = book.childNodes[4]; // Could vary, check for nodeType 4if (cdataNode.nodeType === 4) { console.log("CDATA content: " + cdataNode.nodeValue);}Summary
The DOM Nodes represent every part of the XML document.
Different node types represent elements, attributes, text, comments, CDATA, etc.
You can navigate and manipulate these nodes via DOM APIs.
Want a sample project or code to manipulate these node types?