monksy
monksy

Reputation: 14234

Changing an XPath query from a value within for-each

I'm trying to do a for each on each page:

<xsl:for-each select="/root/page">
   <xsl:value-of select="/root/titles/@page/"/>
</xsl:for-each>

Sample XML;

<root>
  <titles>
   <en>A title</en>
   <de>Ein Titel</de> 
 </titles>
 <page title="de">
    ....
 </page>
</root>

The problem I am having is that the XPath isn't resolving to the /root/titles/de/...
How can I get it to work?

Upvotes: 2

Views: 656

Answers (4)

harpo
harpo

Reputation: 43228

It's not really clear what you want, but it looks like you should be aware that xsl:for-each changes the context to the selected node, just like a template does. So this might get you somewhere:

<xsl:for-each select="/root/page">
   <xsl:value-of select="/root/titles/*[name()=current()/@title]"/>
</xsl:for-each>

Hope this helps.

Upvotes: 1

Emiliano Poggi
Emiliano Poggi

Reputation: 24846

Use xsl:key. Because is not clear the output you need I've provided just an example for you showing how to get the title from titles for each page according to the page language.


XSLT 1.0 tested under Saxon 6.5.5

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="titles" match="titles/*" use="local-name()"/>

    <xsl:template match="/root">
     <xsl:for-each select="page">
             <xsl:value-of select="concat('title-',@title,key('titles',@title),'&#xA;')"/>
     </xsl:for-each>
 </xsl:template>

</xsl:stylesheet>

Applied on this input

 <?xml version="1.0" encoding="UTF-8"?>
<root>
  <titles>
   <en>A title</en>
   <de>Ein Titel</de> 
 </titles>
 <page title="de">
    ....
    </page>
     <page title="en">
    ....
 </page>
</root>

produces:

title-de:Ein Titel
title-en:A title

Tested on Mozilla Firefox 3.6.17 as follows:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test_trans.xsl"?>
<root>
  <titles>
   <en>A title</en>
   <de>Ein Titel</de> 
 </titles>
 <page title="de">
    ....
    </page>
     <page title="en">
    ....
 </page>
</root>

Produces

 title-deEin Titeltitle-enA title

Obviously without new lines, because we are displaying it in a browser and the transform should be changed to produce HTML.

Upvotes: 1

danyolgiax
danyolgiax

Reputation: 13116

updated

 <xsl:for-each select="/root/page">
   <xsl:variable name="language" select="@title"/>
   <xsl:value-of select="/root/titles/*[name()=$language]"/>
</xsl:for-each>

now it works for me!

Upvotes: 1

Andrew Cooper
Andrew Cooper

Reputation: 32596

<xsl:for-each select="/root/page">
    <xsl:variable name="language" select="@title"\>
    <xsl:value-of select="/root/titles/$language"/>
</xsl:for-each>

Upvotes: 0

Related Questions