You can use preceding-sibling in the XPath expression to achieve this.
Here is the sample XML document that you submitted:
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<contact type="friend">
<name>Joe</name>
</contact>
<contact type="friend">
<name>Rick</name>
</contact>
<contact type="foe">
<name>Bob</name>
</contact>
<contact type="friend">
<name>Jeff</name>
</contact>
<contact type="friend">
<name>Mark</name>
</contact>
</contacts>
Assuming that above XML is saved as c:\1.xml, try the following VB 6.0 code (remember to add reference [Project | References] to MSXML 4.0)
Dim objXMLDoc As New MSXML2.DOMDocument40
Dim xmlNodesColl As MSXML2.IXMLDOMNodeList
Dim aNode As MSXML2.IXMLDOMNode
objXMLDoc.async = False
objXMLDoc.validateOnParse = False
If objXMLDoc.Load("c:\1.xml") Then
objXMLDoc.setProperty "SelectionLanguage", "XPath"
Set xmlNodesColl = objXMLDoc.selectNodes( _
"/contacts/contact[not(@type = preceding-sibling::contact/@type)]/@type")
If xmlNodesColl Is Nothing Then
MsgBox "No nodes found"
Else
For Each aNode In xmlNodesColl
MsgBox "Contact Type = " & aNode.Text
Next
End If
Else
MsgBox "Error:" & objXMLDoc.parseError.reason
End If
The XPath expression /contacts/contact[not(@type = preceding-sibling::contact/@type)]/@type selects all the type attribute nodes where none of the preceding siblings contact nodes have the type attribute with the same value as the current type attribute value.
The above code should popup two message boxes with text as:
Contact Type = friend
Contact Type = foe
|