Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple For Eaches or XPath Change? 2

Status
Not open for further replies.

Genimuse

Programmer
May 15, 2003
1,797
US
I'm parsing through an XML document and need to get multiple values from each item. A single item in the XML looks like this:
Code:
  <Customer>
    <ID>1043</ID>
    <Name>Bob Smith</Name>
    <Provider>
      <ProviderID>860</ProviderID>
    </Provider>
  </Customer>
I'm looking for records that match a particular ProviderID (in this example, = 860), so my bit of code looks like this:
Code:
Dim xmlDoc As New System.Xml.XmlDocument()
'Load the file
xmlDoc.Load(AppPath() & "\Customers.xml")
Dim xmlSourceList As System.Xml.XmlNodeList
Dim xmlSourceItem As System.Xml.XmlNode
'List of items that match
xmlSourceList = xmlDoc.SelectNodes("//ProviderID[. = '860']/../../Name")
'Iterate through the list
For Each xmlSourceItem In xmlSourceList
  txtDisplay.Text += vbCrLf & xmlSourceItem.InnerText
Next
This works fine for retrieving the name, but I want to retrieve the Name and the ID. My xpath knowledge is pretty basic, so I don't know if there's a better way to specify it to get both. I can't use "../../*" and get everything due to... well, it's complicated, but I need to be able to specify precisely which named values to return.

I figured I could, if I wanted to, create two XmlNodeLists, one with "../../Name" and one with "../../ID", but I don't know how I could For Each iterate through both a the same time or how to keep them "synched."

Is there some other way to do it?
 
why is providerid in a separate node?



Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Poor schema design. Unfortunately I don't have control over it.
 
Why don't you get the customer node instead, Then you could get the name and ID nodes in the loop using SelectSingleNode method of the node object.

I have not tested this
xmlSourceList = xmlDoc.SelectNodes("//ProviderID[. = '860']/../../../Customer")


xmlSourceList.SelectSingleNode("Name").InnerText
 
Running another XPath query is fairly expensive. You should be able to navigate up one level via the ParentNode property, and then down again via the ChildNodes collection. This is much faster as there's no additional query run.

Or..
Just change your original query to not go down to the Name level:
Code:
"//ProviderID[. = '860']/../Customer"
and use the ChildNodes collection from there.

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top