To demonstrate how to add nodes to an XML DOM (Document Object Model) using JavaScript, I'll provide a simple example. Let's assume we have an XML document and we want to add a new <book>
element with its child elements <title>
, <author>
, <year>
, and <price>
.
Example
<?xml version="1.0"?> <bookstore> <book> <title>Harry Potter and the Philosopher's Stone</title> <author>J.K. Rowling</author> <year>1997</year> <price>10.99</price> </book> <book> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> <year>1937</year> <price>7.99</price> </book> </bookstore>
Example
// Parse the XML string into a DOM object var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xmlString, "text/xml"); // Create elements for the new book var newBook = xmlDoc.createElement("book"); var titleElem = xmlDoc.createElement("title"); var authorElem = xmlDoc.createElement("author"); var yearElem = xmlDoc.createElement("year"); var priceElem = xmlDoc.createElement("price"); // Set text content for the new book elements titleElem.textContent = "The Catcher in the Rye"; authorElem.textContent = "J.D. Salinger"; yearElem.textContent = "1951"; priceElem.textContent = "5.99"; // Append child elements to the new book element newBook.appendChild(titleElem); newBook.appendChild(authorElem); newBook.appendChild(yearElem); newBook.appendChild(priceElem); // Append the new book element to the bookstore element var bookstore = xmlDoc.getElementsByTagName("bookstore")[0]; bookstore.appendChild(newBook); // Convert the updated XML document back to string var serializer = new XMLSerializer(); var updatedXmlString = serializer.serializeToString(xmlDoc); // Output the updated XML string console.log(updatedXmlString);
Parsing XML: Use DOMParser
to parse the XML string into a DOM object (xmlDoc
).
Create Elements: Create new elements (newBook
, titleElem
, authorElem
, yearElem
, priceElem
) using createElement
.
Set Text Content: Set text content for each element using textContent
.
Append Child Elements: Append child elements (titleElem
, authorElem
, yearElem
, priceElem
) to the newBook
element.
Append New Book: Append the newBook
element to the <bookstore>
element in the XML document.
Serialize XML: Convert the updated XML document (xmlDoc
) back to a string using XMLSerializer
.
Output: Log the updated XML string (updatedXmlString
) to the console.
This example demonstrates how to programmatically add nodes (in this case, a new <book>
element) to an existing XML DOM using JavaScript. Adjust the element names, text content, and structure as needed for your specific XML schema and requirements.