Click to See Complete Forum and Search --> : xpath/xml select parent


TheoSqua
05-12-2009, 09:43 PM
So i'm trying to create an ad rotator that works with XML.

My xml is basically this:
<root>
<ad>
<category num="1"></category>
<category num="2"></category>
</ad>
</root>

I have a script that checks the length for each category with a the attribute num that is equal the the category value of the page calling the xml. I.E. if there are eight <ad> elements with <category num='1'> then the page randomly goes from 1-8 to display that ad.

I was calling the ad by doing object.selectSingleNode("//category[@='1'][1]")

This works fine for the first ad, but it only selects elemtnts in the first <ad> node.

How can I have where it would select this: object.selectSingleNode("//category[@="1"][2]"), where the second <category num="1"> element might be in the second, third, or fourth <ad> node?

I tried doing selectSingleNode(*/*/category[@="1"][2]) and that won't work.

I can get the code to work just fine by changing category from a child element of <ad> to an attribute of <ad>, but then I can only give each <ad> element one category, and i'm hoping to give a few of them multiple categories.

Am I making any sense? :)

dmboyd
05-13-2009, 08:02 AM
Use a loop??

The following might work (using JScript since you're using a Microsoft API; other languages aren't drastically different):
var elt_list = object.selectNodes("//category[@num='1']");
for (var index = 0; index < elt_list.Count; ++index) {
// Each category element with [@num='1'] being true should be queryable using elt_list.item(index).
}

I don't know why Microsoft didn't just make it an array or something if it uses an array-like notation... Then again, PHP does the same thing using a similar notation.

I'm sure there is a better way (e.g. enumerating them rather than looping through the results of the selectNodes() call using the item() function/method), but the above should work assuming I'm understanding Microsoft's documentation correctly...and JScript is special where the first letter of the method name is always lowercase... Otherwise your selectSingleNode() call should have failed. ^_^