Thursday, 25 December 2014

How to read XML file from QTP


XMLDataFile = "C:\Documents and Settings\qa\Desktop\TestData.xml"

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)

Set nodes = xmlDoc.SelectNodes("/bookstore/book")
MsgBox "Total books : " & nodes.Length

' get all titles
Set nodes = xmlDoc.SelectNodes("/bookstore/book/title/text()")

' get their values
For i = 0 To (nodes.Length - 1)
    Title = nodes(i).NodeValue
    MsgBox "Title #" & (i + 1) & ": " & Title
Next

Set node = xmlDoc.SelectSingleNode("/bookstore/book[0]/title/text()")
MsgBox "Title of 1st book: " & node.NodeValue

' get list of John Smith's books
Set nodes = xmlDoc.SelectNodes("/bookstore/book/title[../author = 'John Smith']/text()")

' get their titles
For i = 0 To (nodes.Length - 1)
    Title = nodes(i).NodeValue
    MsgBox "Title #" & (i + 1) & ": " & Title
Next

' get list of books published after 2003
Set nodes = xmlDoc.SelectNodes("/bookstore/book/title[@published > 2003]/text()")

' get their titles
For i = 0 To (nodes.Length - 1)
    Title = nodes(i).NodeValue
    MsgBox "Title #" & (i + 1) & ": " & Title
Next



-------------XML file content ------------------

<?xml version="1.0"?>
<bookstore>
    <book>
        <title published="1595">Romeo and Juliet</title>
        <author>William Shakespeare</author>
    </book>
    <book>
        <title published="1997">Yet Another Book</title>
        <author>John Smith</author>
    </book>
    <book>
        <title published="2008">Absolute Knowledge</title>
        <author>John Smith</author>
        <author>Mark Coverdy</author>
    </book>
</bookstore>

No comments:

Post a Comment