Reputation: 622
I have the following xml:
<field_x_position>
<en is_array="true">
<value>60</value>
</en>
<de is_array="true">
<value>70</value>
</de>
</field_x_position>
<field_background_image>
<de is_array="true">
<filename>filename_de.png</filename>
</de>
<en is_array="true">
<filename>filenmae_en.png</filename>
</en>
</field_background_image>
I try to re write it an get the following result
<backgroundImgage>
<en x="60">filename_en.png</en>
<de x="70">filename_de.png</de>
</backgroundImage>
Since there could be added more languages I need to loop over those. How can I select the matching value of the corresponding element since name(.) in a XPath expression isn't working of course.
<xsl:element name="bgImage">
<xsl:for-each select="field_background_image/*">
<xsl:element name="{name(.)}">
<xsl:attribute name="x">
<xsl:value-of select="../../field_x_position/name(.)/item/value"/>
</xsl:attribute>
<xsl:value-of select="item/filename"/>
</xsl:element>
</xsl:for-each>
Thank you so much for your help.
Upvotes: 0
Views: 1794
Reputation: 117175
I would suggest using XSLT's built-in key mechanism for resolving cross-references:
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:key name="x" match="field_x_position/*" use="name()" />
<xsl:template match="/*">
<backgroundImage>
<xsl:for-each select="field_background_image/*">
<xsl:element name="{name()}">
<xsl:attribute name="x">
<xsl:value-of select="key('x', name())/value"/>
</xsl:attribute>
<xsl:value-of select="filename"/>
</xsl:element>
</xsl:for-each>
</backgroundImage>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0
Reputation: 70648
The expression you are looking for is this (Note that there is no item
element in your XML, so I have also removed this from the expression)
<xsl:value-of select="../../field_x_position/*[name() = current()/name()]/value"/>
Alternatively make use of a variable to slightly simplify it. Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/*">
<xsl:element name="bgImage">
<xsl:for-each select="field_background_image/*">
<xsl:variable name="name" select="name()" />
<xsl:element name="{$name}">
<xsl:attribute name="x">
<xsl:value-of select="../../field_x_position/*[name() = $name]/value"/>
</xsl:attribute>
<xsl:value-of select="filename"/>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1