Friday, January 22, 2010

Adding a new node in a XML Document.

Example 3: Adding a new node in a XML Document and displaying all the nodes one at a time in a messagebox.

XML file: Save the below text in a notepad and save it as c.xml.



VBScript code: Save the below text in a notepad and save it as c.vbs.

Creating XMLDOM object and Loading it. The async property specifies whether downloading of an XML file should be handled asynchronously or not. True means that the load() method returns the control to the caller before the download is complete. False means that the download must be completed before the caller gets the control back.
set xml_doc = createObject("Microsoft.XMLDOM")
xml_doc.async = false
xml_doc.load("c:\c.xml")

The createNode method creates a node using the specified type (must be a value that uniquely identifies the node type.), name (the new node's value for the nodeName property) and namespace.
set root = xml_doc.documentElement
set new_book = xml_doc.createNode(1, "Book", "")
set book_text = xml_doc.createNode(3, "", "")
book_text.text = "book-6"
new_book.appendChild(book_text)

below statement is inserting the new node before the second node. See below how the new XML looks after the row is added.
root.insertBefore new_book, root.childNodes.item(2)

xml_doc.save("C:\sa1.xml")

The getElementsByTagName() method returns a NodeList of all elements with a specified name.
set books = xml_doc.getElementsByTagName("Book")
 n_books = books.length

for i=0 to n_books-1
   msgbox books(i).text
next

When you run the above code, along with adding the new node it shows all the nodes in a message box as shown below:



XML after adding the row.



Also See:
Explain XML and XML DOM
VBScript to access number of child nodes and text/nodename of each child node from XML file.
VBScript to access node name and node type of all nodes from XML document.
VBScript to append a string at the end of a text node in XML file.
VBScript to compare two XML files and show the differences in a messagebox.