How to validate XML using using VBScript

XMLDOM is a programming interface to access and manipulate XML documents. The most amazing thing about XMLDOM is that it can be used with any language and operating system.

In order to work with XML, we can leverage XMLDOM to change the structure of xml, read the xml, 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.

Now we will see how we validate an xml file using XMLDOM.

Function to validate xml using vbscript

' 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"
Validate method may be used to specify a Schema file, check whether the loading of the XML file to meet the Schema format, for example, whether derived script check object library the following XML file to meet the requirements of ObjectRepository.xsd:
'Check the XML document meets the specified XML schema
ans = doc.Validate ("D:Program FilesMercury InteractiveQuickTest ProfessionaldatObjectRepository.xsd")
'If the inspection meeting Schema, prompt examination success, make a list of reasons not to meet otherwise
If ans Then
MsgBox "XML file matching the specified Schema!"
errNo = doc.GetValidationErrorsNumber
For i = 1 to errNo
errStr = doc.GetValidationError(i)
MsgBox errStr
End If

How to modify XML using VBScript

The XMLUtil object is used to read the XML file, the LoadFile method loads the xml file so that system can read the text from XML format in the specified file, then it returns a XMLData object, Now we will see how to modify an xml file.

Set xmlDoc = CreateObject("Microsoft.XMLDOM") ' Create a XMLDOM object
xmlDoc.async = False
xmlDoc.load "test.xml" ' Load the XML document
' 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)
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 rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue ' Print the modified nodal values
rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue = "hello!" 'Modify the node value
Print rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue 'Print the modified nodal values
' Save the XML data to another file "test_save.xml"
End If
Set xmlDoc = Nothing

[hfe_template id=’1966′]