As per comments:
what if elements were not in consequent orders?
In this case (assuming XSLT 1.0) you can use translate()
to get the id of the elements and then search for the corresponding elements by correct name built using concat()
. I would change the following-sibling::
axis to the ../
(short for parent::
) to make sure to eventually catch also elements preceding the current firstname
.
<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:template match="customers">
<MyCustomers>
<xsl:apply-templates select="*[starts-with(name(),'firstname')]"/>
</MyCustomers>
</xsl:template>
<xsl:template match="*[starts-with(name(),'firstname')]">
<xsl:variable name="id" select="translate(name(),'firstname','')"/>
<Customer>
<Name><xsl:value-of select="concat(.,' ',
../*[name()=concat('lastname',$id)])"/></Name>
<Sex><xsl:value-of select="../*[name()=concat('sex',$id)]"/></Sex>
</Customer>
</xsl:template>
</xsl:stylesheet>
Obsolete answer
Assuming the fixed input document structure as shown in the question, a fine working XSLT 1.0 transform is:
<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:template match="customers">
<MyCustomers>
<xsl:apply-templates select="*[starts-with(name(),'firstname')]"/>
</MyCustomers>
</xsl:template>
<xsl:template match="*[starts-with(name(),'firstname')]">
<Customer>
<Name><xsl:value-of select="concat(.,' ',
following-sibling::*[1]
[starts-with(name(),'lastname')])"/></Name>
<Sex><xsl:value-of select="following-sibling::*[2]
[starts-with(name(),'sex')]"/></Sex>
</Customer>
</xsl:template>
</xsl:stylesheet>
Little explanation
You need XPath 1.0 function starts-with()
because of the sad name of the tags in your XML input. You can use the following-sibling::
axis to get the required following sibling tags of any element whose name starts with firstname
.