FilterChildElementsByAttr (QTP, TestComplete, XML, VBScript)
Parent page: Service Functions – MSXMLDOM (QTP, TestComplete, VBScript)
Description
Filters parent XML object by removing child XML nodes not matching specified attribute value.
Implementation
'Removes non-matching nodes
Public Function FilterChildElementsByAttr(ByRef objXMLParent, ByVal sTagName, ByVal sAttrName, ByVal sAttr, ByVal objParameter)
	Dim objColl, objNode, objRNode
  Dim Iter, sValue
  Dim boolMatchCase, boolRC
	If objXMLParent is Nothing Then
		Set FilterChildElementsByAttr = Nothing
		Exit Function
	End If
	If TypeName(objParameter) <>  "Dictionary" Then
		Set objParameter = CreateObject("Scripting.Dictionary")
	End If
  boolMatchCase = InitBool(Trim(objParameter.Item("p.matchcase")), False)
  If Not boolMatchCase Then
    sAttr = LCase(sAttr)
  End If
	Set objColl = objXMLParent.SelectNodes("./"&sTagName)
  For Iter = 0 To objColl.Length-1
		Set objNode = objColl.Item(Iter)
		Call GetXMLElementProperty(objNode, "#ATTR:" & sAttrName, -1, sValue)
    If boolMatchCase Then
      boolRC = sValue = sAttr
    Else
      boolRC = LCase(sValue) = sAttr
    End If
    If boolRC Then
      'keep it
    Else
      Set objRNode = objXMLParent.RemoveChild(objNode)
      Set objRNode = Nothing
    End If
  Next
  Set FilterChildElementsByAttr = objXMLParent
End Function
Unit Tests
'Unit tests use other functions from the parent library
'Reporting example is done in TestComplete syntax
  Set objXMLNode = SetChildElementByAttr(objXMLParent, "step", "alpha", "System Step 1")
  Set objXMLNode = SetChildElementByAttr(objXMLParent, "step", "betta", "System Step 2")
  Set objXMLNode = SetChildElementByAttr(objXMLParent, "step", "gamma", "System Step 3")
  Set objXMLParent1 = CopyChildElements(objXMLParent, Nothing)
  Call FilterChildElementsByAttr(objXMLParent1, "step", "name", "gamma", Nothing)
  Set objXMLNode = objXMLParent1.SelectNodes("./step").item(0)
  boolRC = GetXMLElementProperty(objXMLNode, "#text", -1, sValue)
  boolRC = boolRC AND (sValue = "System Step 3")
  If Not boolRC Then
    Log.Error "FilterChildElementsByAttr failed"
  End If
 

