How to add a node in XML DOM

In this articles I am going to explain about add node methods in XML.
  • 2582

Add a node in XML DOM

Add method is define in three types: appendChild, insertBefore, insertData.

appendChild() -Add a child node to an existing node.

Example

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="loadxmldoc.html">

</script>

</head>

<body>

 

<script type="text/javascript">

    xmlDoc = loadXMLDoc("library.xml");

 

    newel = xmlDoc.createElement("Add");

 

    a = xmlDoc.getElementsByTagName("book")[0];

    a.appendChild(newel);

 

    document.write(a.getElementsByTagName("Add")[0].nodeName);

</script>

</body>

</html>

insertBefore() -Insert a node before a specified child node.

Example

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="loadxmldoc.html">

</script>

</head>

<body>

 

<script type="text/javascript">

    xmlDoc = loadXMLDoc("library.xml");

 

    newNode = xmlDoc.createElement("book");

 

    a = xmlDoc.documentElement;

    b = xmlDoc.getElementsByTagName("book");

 

    document.write("Book : " + b.length);

    document.write("<br />");

    a.insertBefore(newNode, b[3]);

 

    b = xmlDoc.getElementsByTagName("book");

    document.write("Book : " + b.length);

</script>

</body>

</html>

insertData() - Method inserts data into an existing text node.

Example

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="loadxmldoc.html">

</script>

</head>

<body>

 

<script type="text/javascript">

    xmlDoc = loadXMLDoc("library.xml");

 

    a = xmlDoc.getElementsByTagName("title")[0].childNodes[0];

    document.write(a.nodeValue);

    a.insertData(0, "Easy ");

    document.write("<br />");

    document.write(a.nodeValue);

 

</script>

</body>

</html>

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.