xslt - Add an attribute to output XML using something similar to call-template -
i've been searching few weeks now, , i've given up. have xslt script output xml file based on xsd definition. problem lies bit of code:
sample input, types can arbitrarily nested:
<xs:element name="rootelement"> <xs:complextype> <xs:sequence> <xs:element ref="r1" minoccurs="0" /> <xs:element ref="r2" minoccurs="0" /> <xs:element ref="r3" minoccurs="0"> <xs:complextype> <xs:sequence> <xs:element ref="r4" minoccurs="0" /> <xs:element ref="r5" minoccurs="0" /> </xs:sequence> </xs:complextype> </xs:element> </xs:sequence> </xs:complextype> </xs:element>
xsl:
<!-- wish work --> <xsl:if test="$minoccurs"> <xsl:attribute name="minoccurs"><xsl:value-of select="$minoccurs"/></xsl:attribute> </xsl:if> <xsl:choose> <xsl:when test="@ref"> <xsl:variable name="elementref" select="current()/@ref"/> <xsl:for-each select="//xs:element[@name=$elementref]"> <xsl:call-template name="element"> <xsl:with-param name="minoccurs" select="./@minoccurs"/> </xsl:call-template> </xsl:for-each> </xsl:when> <!-- abridged --> </xsl:choose> </xsl:template>
output like:
<rootelement> <r1 minoccurs="0" /> <r2 minoccurs="0" /> <r3 minoccurs="0"> <r4/> <r5/> </r3> </rootelement>
i'm doing recursive call , works fine. but, can't add attribute, , i've read online. how can change able add attribute?
given xml input,
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema" elementformdefault="qualified"> <xs:element name="rootelement"> <xs:complextype> <xs:sequence> <!-- replaced original @ref @name --> <xs:element name="r1" minoccurs="0" /> <xs:element name="r2" minoccurs="0" /> <xs:element name="r3" minoccurs="0"> <xs:complextype> <xs:sequence> <xs:element name="r4" minoccurs="0" /> <xs:element name="r5" minoccurs="0" /> </xs:sequence> </xs:complextype> </xs:element> </xs:sequence> </xs:complextype> </xs:element> </xs:schema>
the following xslt,
<?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xs="http://www.w3.org/2001/xmlschema" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="xs:element"> <xsl:element name="{@name}"> <xsl:if test="@minoccurs"> <xsl:attribute name="minoccurs"> <xsl:value-of select="@minoccurs"/> </xsl:attribute> </xsl:if> <xsl:apply-templates/> </xsl:element> </xsl:template> </xsl:stylesheet>
will produce following xml output,
<?xml version="1.0" encoding="utf-8"?> <rootelement> <r1 minoccurs="0"/> <r2 minoccurs="0"/> <r3 minoccurs="0"> <r4 minoccurs="0"/> <r5 minoccurs="0"/> </r3> </rootelement>
as requested.
Comments
Post a Comment