Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match conditionally upon current node value

Given the following XML:

<current>
  <login_name>jd</login_name>
</current>
<people>
  <person>
    <first>John</first>
    <last>Doe</last>
    <login_name>jd</login_name>
  </preson>
  <person>
    <first>Pierre</first>
    <last>Spring</last>
    <login_name>ps</login_name>
  </preson>
</people>

How can I get "John Doe" from within the current/login matcher?

I tried the following:

<xsl:template match="current/login_name">
  <xsl:value-of select="../people/first[login_name = .]"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
like image 270
Pierre Spring Avatar asked Sep 15 '08 08:09

Pierre Spring


2 Answers

I'd define a key to index the people:

<xsl:key name="people" match="person" use="login_name" />

Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the <person> elements based on their <login_name> child.

I'd have a template that returned the formatted name of a given <person>:

<xsl:template match="person" mode="name">
  <xsl:value-of select="concat(first, ' ', last)" />
</xsl:template>

And then I'd do:

<xsl:template match="current/login_name">
  <xsl:apply-templates select="key('people', .)" mode="name" />
</xsl:template>
like image 111
JeniT Avatar answered Sep 17 '22 15:09

JeniT


You want current() function

<xsl:template match="current/login_name">
  <xsl:value-of select="../../people/person[login_name = current()]/first"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../../people/person[login_name = current()]/last"/>
</xsl:template>

or a bit more cleaner:

<xsl:template match="current/login_name">
  <xsl:for-each select="../../people/person[login_name = current()]">
    <xsl:value-of select="first"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="last"/>
  </xsl:for-each>
</xsl:template>
like image 38
jelovirt Avatar answered Sep 17 '22 15:09

jelovirt