May 27, 2021 XML DOM
The following example uses the XML
file .xml.
The
function loadXMLDoc(),
located in an external JavaScript, is used to load XML files.
Create an element node
This example uses createElement() to create a new element node and adds it to a node using appendChild().
Create property nodes using createAttribute
This example uses createAttribute() to create a new property node and inserts it into an element using setAttributeNode().
Create a property node with setAttribute
This example uses setAttribute() to create a new property for an element.
Create a text node
This example uses createTextNode() to create a new text node and add it to an element using appendChild().
Create a CDATA section node
This example uses createCDATAsection() to create a CDATA section node and add it to an element using appendChild().
Create a comment node
This example uses createComment() to create a comment node and adds it to an element using appendChild().
CreateElement() method to create a new element node:
Example explanation:
Traverse and add an element to all the elements:
Try
CreateAttribute() is used to create a new property node:
Example explanation:
Traverse all the elements and add a new property node: Try it
Note: If the property already exists, it is replaced by the new property.
Since the setAttribute() method can create a new property without the property being present, we can use this method to create a new property.
Example explanation:
Traverse all the elements and add a new property: Try
CreateTextNode() method to create a new text node:
Example explanation:
Add an element node with a text node to all the elements: Try
CreateCDATASection() method to create a new CDATA section node.
Example explanation:
Traverse and add a CDATA section to all the elements:
Try
CreateComment() method to create a new comment node.
Example explanation:
Loop and add a comment node to all the elements:
Try
When you create new nodes, there are several ways to insert them into the tree, and we'll describe how to insert them in the next section.