XML using VBScript : How to Read, Write and Modify
We can work with XML using VBScript in different ways. One way is by leveraging XMLDOM. XMLDOM is a programming interface to access and manipulate XML documents. In this blog post we will learn how to work with XML using VBScript. The most amazing thing about XMLDOM is that it can be used with any language and operating system.
It allows us to change the structure of XML and read the XML. Additionally, we can write new nodes or elements in the XML.
DOM will be the entire XML document as a tree, a document level element is the root of the tree.
XMLDOM contains four main objects:
- XMLDOMDocument
- XMLDOMNode
- XMLDOMNodeList
- XMLDOMNamedNodeMap.
Each XMLDOM object has its own characteristics and methods. Let’s see how we can leverage them.
Now we will see how to validate an xml using VBScript and XMLDOM.
Validate XML using and XMLDOM
We use XMLUtil object to read the XML file. The LoadFile method loads the xml file. System reads the text in XML format from the specified file.
Example code to read XML
' The CreateXML method uses the XMLUtil object to create a XMLData object
Set doc = XMLUtil.CreateXML()
' Loading XML file used to check
doc.LoadFile "Test.XML"
'Check the XML document meets the specified XML schema
ans = doc.Validate ("D:Program Files\sample.xsd")
'If the inspection meeting Schema, prompt examination success, else make a list of 'failing reasons
If ans Then
MsgBox "XML file matching the specified Schema!"
else
errNo = doc.GetValidationErrorsNumber
For i = 1 to errNo
errStr = doc.GetValidationError(i)
MsgBox errStr
Next
End If
Modify XML using VBScript and XMLDOM
Now we will see how to modify an xml file. The first step is to create an object of XMLDOM and then load the xml as before.
Once the xml is loaded, only then we modify the nodes as per our requirement. As shown below, we traverse through the nodes by using index of the nodes. In the below example we have used print statement as per UFT/QTP.
Example code to modify XML
' Create a XMLDOM object
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Load the XML document
xmlDoc.load "test.xml"
' Check if there is an error in XML document
If xmlDoc.parseError.errorCode <> 0 Then
Set myErr = xmlDoc.parseError
MsgBox("XML Loads Failed. " & myErr.reason)
Else
Set rootNode = xmlDoc.documentElement
' Change the value of an attribute of the specified node XML
rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue = "E-Mail"
' Print the modified nodal values
Print rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue
'Modify the node value
rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue = "hello!"
'Print the modified nodal values
Print rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue
' Save the XML data to another file
xmlDoc.save "test_save.xml"
End If
Set xmlDoc = Nothing