Search code examples
xmlxsltxslt-1.0contains

Get a node that contains X string


I am a litle stucked trying to get the node that contains certain string value. It seems easy, using the node[contains(., X)], but the problem is that this formula I am getting nodes that are not exactly the specifed because of this:

<node>FLT10 FLT3</node>
<node>FLT1 FLT2</node>

To search the node, I only have one of its possibles values (in this case: FLT1 or FLT2 or FLT10 or FLT3), so the simply contains will work looking for FLT10, FLT3 and FLT2, but not for FLT1 because in this case the contains return the node with FLT10 beacuse (obviosly) it contains FLT1. I tried doing:

[contains(., concat($the_ref, ' '))]

The first step was try to add a whitespace, and then it starts to work to FLT10 and FLT1 but not for FLT3 and FLT2. My second, and stupid, step was this:

[contains(., concat($the_ref, ' ')) or contains(., concat($the_ref, '&lt;'))]

and... well... let´s say that I didn´t get the expected results :/

Any idea how I could do this??

Thanks in advance.

PD: I am using xslt 1.0


Solution

  • Consider the following example:

    XML

    <input>
        <node>FLT10 FLT3</node>
        <node>FLT1 FLT2</node>
        <node>FLT4 FLT1</node>
        <node>FLT5 FLT11</node>
    </input>
    

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:template match="/input">
        <result>
            <xsl:copy-of select="node[contains(concat(., ' '), 'FLT1 ')]" />
        </result>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    <?xml version="1.0" encoding="UTF-8"?>
    <result>
      <node>FLT1 FLT2</node>
      <node>FLT4 FLT1</node>
    </result>
    

    P.S. A better solution would be to change the input format.


    Note: A more robust solution would do:

    [contains(concat(' ', ., ' '), ' FLT1 ')]
    

    to prevent false positives from both sides.