Monday, December 3, 2012

How to work with XML Files - Part 1

Here in this video i demonstrated how to traverse an XML file using "XMLUtil" utility object.
Following is the code i used in the above examples:
'***************************************************************************************************************************************************************************************
'Objective              :  Cover basic XML Operations
'Functionality        : The below script  covers the updating off XML Files
'                                  
'Author                    : Udaya Anem
'Scripted on       : 18th Sept
'Updated by         :
'***************************************************************************************************************************************************************************************
Dim o_XML
Dim s_XMLFilePath

s_XMLFilePath="E:\Programming Samples\QTP Samples\Cars.xml"
s_UpdatedXMLFilePath="E:\Programming Samples\QTP Samples\Cars2.xml"

'Set o_XML=XMLUtil.CreateXMLFromFile(s_XMLFilePath)
Set o_XML=XMLUtil.CreateXMLFromFile(s_XMLFilePath)

'The below steps update specified XML Element value
'Set o_ChildPath=o_XML.ChildElementsByPath("/Cars/Make/Model/Name")
'print o_ChildPath.Item(1).Value
'o_ChildPath.Item(1).SetValue("Alto")
'o_XML.SaveFile s_UpdatedXMLFilePath
'print o_ChildPath.Item(1).Value

'The below script adds an attribute to the XML Element
Set o_ChildPath=o_XML.ChildElementsByPath("/Cars/Make/Model/Name")
o_ChildPath.Item(1).AddAttribute "Version","Petrol"
o_XML.SaveFile s_UpdatedXMLFilePath
'
'
'set o_XMLAttributes=o_ChildPath.Item(1).Attributes
'print o_XMLAttributes.Item(1).Value

'to update an attribute also we have to use AddAttribute
o_ChildPath.Item(1).AddAttribute "Version","Diesel"
o_XML.SaveFile s_UpdatedXMLFilePath

Set o_ChildPath=nothing
Set o_XML=nothing


Following is the sample XML File:
<Cars>
  <Make name="Maruthi">
    <Model>
      <Name>Wagnor</Name>
      <Release>2000</Release>
    </Model>
  </Make>
  <Make name="Hundai">
    <Model>
      <Name>i10</Name>
      <Release>2003</Release>
    </Model>
  </Make>
  <Make name="Maruthi">
    <Model>
      <Name>Swift</Name>
      <Release>2005</Release>
    </Model>
  </Make>
</Cars>

No comments:

Post a Comment