Friday, January 22, 2010

Accessing number of childnodes and text/nodename of each child node.

Example 1: Accessing number of childnodes and text/nodename of each child node from an XML file.

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



VBScript code: Save the below text in a notepad and save it as a.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 objXMLDoc = CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load("c:\a.xml")

Dim root, i
The documentElement property of the XML document is the root node.
Set root = objXMLDoc.documentElement
msgbox "No. of child nodes: "& root.childNodes.length

childNodes property: simplifies retrieving a collection of child nodes. Before you start looping through the collection of child nodes, it’s a good idea to use the length property to determine how many elements the collection contains.
For i = 0 To (root.childNodes.length)-1
msgbox(root.childNodes.item(i).text)
Next


Now go to command prompt and run this above a.vbs file. Make sure the location of xml file in the a.vbs file (3rd line) is correct.

Result of running the above code:



Above it shows child nodes as 2 because as you can see above EmployeeSales is the root and it has 2 child nodes.

In the two messages boxes below it shows text of the two child nodes.








The DOM presents a document as a hierarchy of node objects.

There are many different Node Types: Document (Represents the entire document (the root-node of the DOM tree)),DocumentFragment, DocumentType, ProcessingInstruction, EntityReference, Element, Attr, Text, CDATASection, Comment (Represents a comment), Entity, Notation.

Also See:
Explain XML and XML DOM
VBScript to access node name and node type of all nodes from XML document.
VBScript to add a new node in 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.