Reputation: 458
i have xml:
<graph>
<node id="a" />
<node id="b" />
<node id="c" />
<node id="d" />
<link from="a" id="link1" to="b"/>
<link from="b" id="link2" to="d"/>
<link from="d" id="link3" to="c"/>
</graph>
i want to transform it by xslt to next xml:
<graph>
<node id="a">
<link id="link1" to="b">
</node>
<node id="b">
<link id="link2" to="d">
</node><node id="c">
<node id="c"/>
<node id="d">
<link id="link3" to="c">
</node>
</graph>
i wrote xslt which inlcudes next part:
<xsl:template match="//node">
<xsl:element name="link">
<xsl:attribute name="to">
<xsl:value-of select="//link[@from = self::node()/@id]/@to"></xsl:value-of>
</xsl:attribute>
<xsl:apply-templates />
</xsl:element>
</xsl:template>
but this didn't work. what i'm doing wrong ?
Upvotes: 1
Views: 71
Reputation: 33638
Your XSLT only creates link
elements, but you somehow have to create graph
and node
elements as well. Also, self::node()
in a predicate doesn't work as you expect. Use the current()
function instead.
To solve your task, it's a good idea to start with an identity transform and add templates for nodes that need special handling. Here's an example:
<!-- Identity transform -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="graph">
<xsl:copy>
<!-- Only process node children -->
<xsl:apply-templates select="node"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node">
<xsl:copy>
<!-- Also process matching links -->
<xsl:apply-templates select="@* | //link[@from = current()/@id]"/>
</xsl:copy>
</xsl:template>
<!-- Don't copy @from attribute of links -->
<xsl:template match="link/@from"/>
Upvotes: 1