tags:

views:

1307

answers:

3

Is there a way to find a node matched on part of a value.

If I have the following:

<competition id="100" name="Barclays Premier League"/>
<competition id="101" name="CocaCola Championship" />
<competition id="102" name="CocaCola League 1" />

Given the string "Premier League" or even "Prem", how would I match the correct node and get id 100.

I have managed this using for-each and contains, but this is very inefficient and does not work fast enough for our requirements.

+12  A: 

String handling is not something XSLT is amazing at but there are a few options.

In this case you might try:

//competition[contains(@name,'Prem')]

see here for more options and details

annakata
And if you want just the id then //competition[contains(@name,"Prem")]/@id
Andrew Cox
bah - too used to working with nodesets
annakata
the "//" is probably inadvisable too before anyone else mentions it - I just didn't know any other structure to path on obviously.
annakata
Annakata, I think you're a little bit wrong about the string-handling capabilities of XSLT. Do have a look at my blog where you'll find a few interesting examples to the contrary. :) Cheers
Dimitre Novatchev
@Dimitre - I make that statement in reference to really solid string-feature languages like perl and JS, and with the awkwardness of tasks like string.replace in mind. I love XSLT as much as the next XSLT fanboy :)
annakata
@Annacata, nice to here you're an XSLT fan :) But really, I've done spelling checking, concordance building, solved Tim Bray's Wide Finder in just 22 lines, provided a general LR parser, used it to parse JSON and XPath 2 ... all that in pure XSLT. What other string-processing challenge do we need?
Dimitre Novatchev
@dimitre - impressed by spell checking. I would suggest though that just because something is possible doesn't mean it's efficient. You can't tell me search-and-replace in XSLT is elegant. I'd be interested to see how your pure XSLT approach benchmarks vs (e.g.) .net xslt extension arguments.
annakata
@Annacata, it is not the language but the algorithm used. I guess that the XPath 2.0 standard function replace(), which uses RegEx-s will not be very different in efficiency than a .NET extension function. Of course, in .NET one will have to use (for now) a non-MS product, such as Saxon.NET
Dimitre Novatchev
+1  A: 

There is also a "matches" function, which uses regular expressions, but this is only available in XSL 2.0.

darasd
+5  A: 

Use:

    //competition[contains(@name, 'Prem')]/@id

In other situations such functions as: starts-with() or ends-with() (XPath 2.0 only) can be useful.

Dimitre Novatchev