Thursday, February 17, 2011

Reading XML Attribute Values

Scripting to read the content from an XML could be tricky as there can be many ways suggested out there in internet to do the same task. This, I would say is due the different possible usages in MS VBScript language.

I had a situation where I had to automate a Sterling application which had an XML thrown out and I had to read it in QTP. The situation was like this.

The portion of output XML:
xml version="1.0" encoding="UTF-8" ?>

<Items totalItems="14">
 <Item itemID="12345">
    <InventoryInfo description="door paint">
        <AdditionalInfo ExtendedDescription="lunar mist" />
    </InventoryInfo>
</Item>
<Item itemID="54321">
    <InventoryInfo description="window tint">
        <AdditionalInfo ExtendedDescription="dark blue" />
    </InventoryInfo> 
</Item>
 </Items>


Here in the XML the data is actually within the attributes rather than as values associated with tags. So it becomes very important to read the attribute of each node for all the set of similar nodes in the XML.

I wrote a simple function to solve this:

Firstly in the main script or business component declare a scalar variable.
Dim itemArray
'note that I am not declaring it as a dynamic array with a (). see my previous post for more info on this

'get data to get the entire xml from the screen into a string
outputXML = Browser("browserName").Page("PageName").WebXML("itemXML").GetData
Set xmlObject = CreateObject("Microsoft.XMLDOM")

'select single root element to get total number of records
Set node = xmlObject.DocumentElement.selectSingleNode("//Items")
numNodes = node.GetAttribute("totalItems")
'---one way of getting an attribute of a single node

'now off to the array assignment to get all node attribute values into an array
pNode = "InventoryInfo"
cNode = "AdditionalInfo"
attributeName = "ExtendedDescription"
arraySize = numNodes -1
itemIDArray = fun_GetAttributesFromXML (xmlObj, pNode, cNode, attributeName, arraySize)


And here is the function:

Function fun_GetAttributesArray(xmlObj, pNode, cNode, attr, arrSize)
    Dim nodeList
    Dim numnodes
    Dim currentNode
    Dim iLoopIndex
    Dim attributeArray()


ReDim attributeArray(arrSize)
Set nodeList = xmlObj.DocumentElement.SelectNodes("//" & pNode & "/" & cNode)
numNodes = nodeList.Length
If numNodes > 0 Then
For iLoopIndex = 1 to numNodes
Set currentNode = nodeList.nextNode
attributeArray(iLoopIndex-1) = currentNode.getAttribute(attr)
Next
End If
fun_GetAttributesArray = attributeArray    
End Function

This function returns the attribute value of the cNode that is sent to this function from the entire XML.
The output with the above example will be an array returned by this function with values:
itemIDArray (0) = "lunar mist"
itemIDArray (1) = "dark blue"

No comments: