XML DOM Remove Node - XML DOM

How to remove the node operation from XML DOM?

The remove node operation is used to remove the specified nodes from the document. The nodes that are to be removed are text node, element node and an attribute node.

The methods used for remove node operation are:

  • removeChild()
  • removeAttribute()

removeChild()

The child node that is indicated by the oldChild is removed from the list of children by removeChild() method. Removing child node implies removing text node. Hence when a child node is removed, the associated text node is removed.

Syntax

The syntax to use removeChild() is as follows −

Where,

  • oldChild − is the node being removed.
  • This method returns the node removed.

Example - Remove Current Node

An XML document node.xml is parsed into an XML DOM object and the specified node <ContactNo> is removed from the parent node.

In the above example −

  • x = xmlDoc.getElementsByTagName("ContactNo")[0] gets the element <ContactNo> indexed at 0.
  • x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node.

Execution

The file is saved as removecurrentnode_example.htm on the server path and this file should be on the same path as that of node.xml in the server. The output appears as follows:

Example - Remove Text Node

An XML document node.xml is parsed into an XML DOM object and the specified child node <FirstName> is removed.

In the above example −

  • x = xmlDoc.getElementsByTagName("FirstName")[0]; − gets the first element <FirstName> to the x indexed at 0.
  • y = x.childNodes[0]; − in this line y holds the child node to be remove.
  • x.removeChild(y); − removes the specified child node.

Execution

The file is saved as removetextNode_example.htm on the server path and this file should be on the same path as that of node.xml in the server. The output appears as follows:

removeAttribute()

An attribute of an element is removed by the removeAttribute() method by using its name.

Syntax

Syntax to use removeAttribute() is as follows −

Where,

  • name − is the name of the attribute to remove.

Example

An XML document node.xml is parsed into an XML DOM object and the specified attribute node is removed.

In the above example −

  • document.write(x[1].getAttribute('category')); − value of attribute category indexed at 1st position is invoked.
  • x[1].removeAttribute('category'); − removes the attribute value.

Execution

The file is saved as removeelementattribute_example.htm on the server path and this file should be on the same path as that of node.xml in the server. The output appears as follows:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

XML DOM Topics