Tuesday, 21 January 2014

How to update XML file from QTP !!!

We will use this XML file:

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

Let's check how to update different values in above XML file:

1.How to rename the title of first book?

The QTP script is:

Const XMLDataFile = "C:\TestData.xml"
Const XMLNewFile = "C:\TestData2.xml"

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

' update the title of the first book
Set node = xmlDoc.SelectSingleNode("/bookstore/book[0]/title")
node.Text = "Romeo and Juliet - Salvation" 

' save changes 
xmlDoc.Save(XMLNewFile)

=====================================
<?xm version="1.0"?>
<bookstore>
<book>
<title published="1595">Romeo and Juliet--Salvation</ttle>
<author>William Shakespeare</author>
</book>
=============================================

Note: The numeration begins from zero. That's why I use book[0] to access first item.

How to change the year of second book?

I skip the opening and saving of XML file (see above QTP script). I show only the essence:
' update the attribute of the second book
Set node = xmlDoc.SelectSingleNode("/bookstore/book[1]/title/@published") 
node.Text = "2009" 

And the result is:

<book>
<title published="2009">Absoulute Knowledge</title>
<author>Jhon Smith</author>


1.Note: Use @ to access an attribute of XML node.

2.How to add new author add its new attribute?

QTP script:

' select a parent node
Set parentNode = xmlDoc.SelectSingleNode("/bookstore/book[2]")

' add a new author
Set newNode = xmlDoc.CreateElement("author")
newNode.Text = "Mr. Noname"
parentNode.AppendChild (newNode)

And the result is:

<book>
<title published="2008">Absoulute Knowledge</title>
<author>Jhon Smith</author>
<author>Mark Coverdy</author>
<author>Mr.Noname</author>
</book>
</bookstore>

As you can see, we've added "Mr. Noname" as the new author.

3.How to add new attribute for author (XML node)?

QTP script:
' select a parent node
Set parentNode = xmlDoc.SelectSingleNode("/bookstore/book[2]")

' add its attribute
Set newAttrib = xmlDoc.CreateAttribute("bestseller")
newAttrib.Text = "yes"
parentNode.Attributes.SetNamedItem(newAttrib)

The result is:

<book  bestseller="yes">
<title published="2008">Absoulute Knowledge</title>
<author>Jhon Smith</author>
<author>Mark Coverdy</author>
</book>
</bookstore>
================================
New attribute of a boof and its value ("bestseller"="yes") have been added.

Well, the working with XML files from QTP is easy enough.

--Sudhakar.Mangi

No comments:

Post a Comment