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 Remove Nodes:



Sure, removing nodes from an XML DOM (Document Object Model) involves selecting the nodes you want to delete and then removing them from the document structure. Here's a simple explanation with an example:

Example XML Document

Consider the following XML document (data.xml):

        

Example

<library> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> </book> <book> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> </book> <book> <title>1984</title> <author>George Orwell</author> </book> </library>

Removing Nodes Using JavaScript (for Web Environment)

If you're working with JavaScript in a web environment, you can use the browser's DOM API to manipulate XML documents just like HTML documents. Here’s how you can remove a <book> node from the XML:

          

Example

// Load the XML document var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; // Select the node(s) you want to remove var books = xmlDoc.getElementsByTagName("book"); // Assuming you want to remove the second book node (index 1) var bookToRemove = books[1]; // Remove the node bookToRemove.parentNode.removeChild(bookToRemove); // Output the modified XML console.log(xmlDoc.documentElement.outerHTML); } }; xhttp.open("GET", "data.xml", true); xhttp.send();

Explanation

  1. Load the XML Document: Use XMLHttpRequest to load the XML file (data.xml in this case).

  2. Select Nodes: Use getElementsByTagName() to get all <book> elements.

  3. Remove a Node: Choose the specific <book> element you want to remove (in this case, the second one at index 1). Use parentNode.removeChild() to remove it from its parent node (<library>).

  4. Output: Finally, you can log or use xmlDoc.documentElement.outerHTML to see the modified XML structure.

Important Notes

By following these steps, you can effectively remove nodes from an XML DOM structure using JavaScript.




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