Dictionary对象与XML文件之间的导入导出

 

参考:

Saving and Loading dictionary objects to/from XML

http://knowledgeinbox.com/articles/qtp/advanced-qtp/saving-and-loading-dictionary-objects-tofrom-xml/

 


两个函数: 

'Function: LoadDictionary
'Website: http://KnowledgeInbox.com
'Author: Tarun Lalwani
'Description: Load Dictionary object from a XML file
'Parameters:
'@oDic: The Dictionary object in which the values need to be loaded
'@FileName: The XMLfile path from where the dictionary needs to be loaded
'Return value:
'The oDic dictionary object
 
Function LoadDictionary(oDic, FileName)
 'Exit if the file doesn't exist
 If Not CreateObject("Scripting.FileSystemObject").FileExists(FileName) Then Exit Function
 Dim allKeys, sKey
 
 allKeys = oDic.Keys
 
 'Load the XMLfile
 Set oXML = XMLutil.CreateXMLFromFile (FileName)
 Set oRoot = oXML.GetRootElement
 
 'Load all XML variables
 Set allElements = oRoot.ChildElementsByPath("//Variable")
 Dim oElement
 
 'Enumerate and populate each dictionary key
 For i = 1 to allElements.Count
  Set oElement = allElements.Item(i)
  sKey = oElement.ChildElementsByPath("Name").Item(1).CDATASections.Item(1)
  sValue = oElement.ChildElementsByPath("Value").Item(1).CDATASections.Item(1)
  oDic(sKey) = sValue
 Next
End Function
 
 
'Function: LoadDictionary
'Website: http://KnowledgeInbox.com
'Author: Tarun Lalwani
'Description: Save dictionary object to a XML file
'Parameters:
'@oDic: The Dictionary object for which the values need to be exported as XML
'@FileName: The XMLfile path where the dictionary needs to be saved
'Return value:
'The oDic dictionary object
Sub  SaveDictionary(oDic, FileName)
 Dim allKeys, sKey
 
 allKeys = oDic.Keys
 
 'Create the XML file
 Set oXML = XMLutil.CreateXML ("Dictionary")
 Set oRoot = oXML.GetRootElement
 
 'Enumerate through all dictionary items and save them one by one
 For each sKey in allKeys
  oRoot.AddChildElementByName "Variable",""
  Set oElem =oRoot.ChildElements.Item(oRoot.ChildElements.Count)
  oElem.AddChildElementByName "Name", ""
  oElem.AddChildElementByName "Value", ""
  oElem.ChildElementsByPath("Name").Item(1).AddCDATASection sKey
  oElem.ChildElementsByPath("Value").Item(1).AddCDATASection oDic(sKey)
 Next
 
 'Save the file to sepcified location
 oXML.SaveFile FileName
End Sub

 

使用方法:

Set oDictionary = CreateObject("Scripting.Dictionary")
oDictionary("Name") = "Tarun Lalwani"
oDictionary("Profession") = "QTP Learner"
 
SaveDictionary oDictionary, "C:\MyDictionary.xml"
 
Set oDictionaryFile = CreateObject("Scripting.Dictionary")
LoadDictionary oDictionaryFile, "C:\MyDictionary.xml"
 
Print "Name: " & oDictionaryFile("Name")
Print "Profession: " & oDictionaryFile("Profession")

 

posted on 2011-01-02 21:41  TIB  阅读(1003)  评论(0编辑  收藏  举报

导航