How to query XML by Attribute Index Using XMLDom

530 views Asked by At

I am trying to query an XML File in order to get the attribute values for a specific element.

This works fine when the element has a unique set of attribute e.g.

<parent>
<child code="REWC" curr="PLN" amt="1000"/>
</parent>

In order to query the above I use:

  • object = Microsoft.XMLDOM
  • getElementsByTagName OR selectSingleNode method
  • Once I have that, I run the 'getAttribute' method, which gives me what I need

code snippet:

Set ElementValue = m_objXmlDom.selectSingleNode("//Txn[" & p_intIndex & "]/" & p_strElementName & " ")

'set attribute value
strAttributeValue = ElementValue.getAttribute(p_strAttributeName)

However, I am now in a situation where the XML looks as per below:

<parent>
<child code="REWC" curr="PLN" amt="1000"/>
<child code="xxxx" curr="EUR" amt="1500"/>
<child code="yyyy" curr="GBP" amt="1700"/>
</parent>

Is there a simple way to iterate through each attribute, get the value, and then I can do something with it. I am looking for something like:

.getAttribute(code)[0]
.getAttribute(code)[1]
.getAttribute(code)[2]

Something like the above will print out all the values for all attributes. But Im not to sure how to index at the attribute level.

Any help would be great. I am using VBScript with Microsoft XMLDom.

1

There are 1 answers

0
Sudhir On

Ok, I have gotten around the issue now by doing a for loop in order to iterate over all of the elements that have been returned, and then reading in each attribute. If the attribute matches the one I am looking for then I exit the for loop.

if there is a better way of doing this, then please share any answers, in the meantime my code is working as per below.

Code snippet:

Set Data = m_objXmlDom.getElementsByTagName(".//Txn[" & p_intIndex & "]/" & p_strElementName & "/" & p_strSubElementName & "")

'loop through each one
For Each DataItem in Data
    strTemp1 = DataItem.getAttribute("code")
    strTemp2 = DataItem.getAttribute("curr")
    strTemp3 = DataItem.getAttribute("amt")

    If strTemp1 = strExpectedValue Then
        'set the values
        m_strTemp1 = strTemp1 
        m_strTemp2 = strTemp2 
        m_strTemp3 = strTemp3 
        'set pass flag
        blnDataFound = True
        Exit For
    End If
Next