Public Function Xpath(ByRef objNode As MSXML2.IXMLDOMElement) As String
' returns path of objNode:
' aa/bb/cc
Dim objTestNode As MSXML2.IXMLDOMNode
Dim strPath As String
If objNode Is Nothing Then
' you might implement some error-handling
Else
' concatenate nodenames in loop through parent-axis
' stop looping at the 'document'-node
Set objTestNode = objNode
Do Until objTestNode.nodeType = NODE_DOCUMENT
strPath = "/" & objTestNode.nodeName & strPath
Set objTestNode = objTestNode.parentNode
Loop
' remove the first slash
strPath = Right$(strPath, Len(strPath) - 1)
End If
' dont trust garbage-collection in VB
Set objTestNode = Nothing
' set returnvalue
Xpath = strPath
End Function
Public Function UniqueXpath(ByRef objNode As MSXML2.IXMLDOMElement) As String
' returns unique Xpath to objNode:
' aa[position()=1]/bb[position()=3]/cc[position()=2]
Dim objTestNode As MSXML2.IXMLDOMNode
Dim objPreviousNode As MSXML2.IXMLDOMNode
Dim strPath As String
Dim intPosition As Integer
If objNode Is Nothing Then
' you might implement some error-handling
Else
' concatenate nodenames in loop through parent-axis
' stop looping at the 'document'-node
Set objTestNode = objNode
Do Until objTestNode.nodeType = NODE_DOCUMENT
' determen position by counting previous siblings with the same name
intPosition = 1
Set objPreviousNode = objTestNode.previousSibling
Do Until objPreviousNode Is Nothing
If objPreviousNode.nodeName = objTestNode.nodeName Then
intPosition = intPosition + 1
End If
Set objPreviousNode = objPreviousNode.previousSibling
Loop
strPath = "/" & objTestNode.nodeName & "[position()=" & intPosition & "]" & strPath
Set objTestNode = objTestNode.parentNode
Loop
' remove the first slash
strPath = Right$(strPath, Len(strPath) - 1)
End If
' dont trust garbage-collection in VB
Set objTestNode = Nothing
Set objPreviousNode = Nothing
' set returnvalue
UniqueXpath = strPath
End Function