Reputation: 305
I'm very new to XSLT, and I'd like to know how to create a node based on the text of another node. For example, if have the XML:
<axis pos="6" values="3">
<title>Device</title>
<label code="7">Autologous Tissue Substitute</label>
<label code="J">Synthetic Substitute</label>
<label code="K">Nonautologous Tissue Substitute</label>
</axis>
I'd like to transform it into:
<stuff>
<Device pos="6" code="7">Autologous Tissue Substitute</Device>
<Device pos="6" code="J">Synthetic Substitute</Device>
<Device pos="6" code="K">Nonautologous Tissue Substitute</Device>
</stuff>
I've tried the following XSLT, but it just spews errors at me:
<xsl:template match="axis">
<stuff>
<xsl:apply-templates select="label" />
</stuff>
</xsl:template>
<xsl:template match="label">
<xsl:element name="{../title}">
<xsl:value-of select="text()" />
</xsl:element>
<xsl:attribute name="pos">
<xsl:value-of select="../@pos" />
</xsl:attribute>
<xsl:attribute name="code">
<xsl:value-of select="@code" />
</xsl:attribute>
</xsl:template>
Upvotes: 0
Views: 146
Reputation: 163322
I would do:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="axis">
<stuff>
<xsl:apply-templates select="label" />
</stuff>
</xsl:template>
<xsl:template match="label">
<xsl:element name="{../title}">
<xsl:copy-of select="@code | ../@pos" />
<xsl:value-of select="." />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1
Reputation: 305
This seems to work:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:template match="/root">
<xsl:apply-templates select="axis" />
</xsl:template>
<xsl:template match="axis">
<stuff>
<xsl:apply-templates select="label" />
</stuff>
</xsl:template>
<xsl:template match="label">
<xsl:element name="{../title}">
<xsl:attribute name="pos">
<xsl:value-of select="../@pos" />
</xsl:attribute>
<xsl:attribute name="code">
<xsl:value-of select="@code" />
</xsl:attribute>
<xsl:value-of select="." />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0
Reputation: 116993
How about:
<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="/">
<root>
<xsl:for-each select="axis/label">
<xsl:element name="{../title}">
<xsl:attribute name="pos">
<xsl:value-of select="../@pos" />
</xsl:attribute>
<xsl:attribute name="code">
<xsl:value-of select="@code" />
</xsl:attribute>
<xsl:value-of select="." />
</xsl:element>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0