json - XSL check if some specific outpur were already generated -
i'm trying convert existing xml files json structure using xsl. depending on values, need put elements json array. produce json string correct syntax, need dynamically decide whether put comma behind (or in front) object, since json doesn't allow trailing commas in arrays.
the xml files following:
<list> <type_a> <active>0</active> <data_a>don't put me json...</data_a> </type_a> <type_b> <active>1</active> <data_b>put me json</data_b> </type_b> <type_c> <active>1</active> <data_c>me too...</data_c> </type_c> </list> the xsl convert looks following:
<xsl:template match="/list"> [ <xsl:if test="type_a/active != 0"> { "type": "type_a", "data": <xsl:value-of select="type_a/data_a" /> } </xsl:if> <xsl:if test="type_b/active != 0"> { "type": "type_b", "data": <xsl:value-of select="type_b/data_b" /> } </xsl:if> <xsl:if test="type_c/active != 0"> { "type": "type_c", "data": <xsl:value-of select="type_c/data_c" /> } </xsl:if> ] </xsl:template> the problem is, need put commas between different { } objects, not after last active one. 2 solutions see are, either check if of preceding objects active, before putting object (<xsl-if test="type_a/active != 0 or type_b/active != 0">, </xsl-if>; in front of third object) or transfer xml some, less odd, intermediate xml first. particular first option extremely ugly, since in reality have check far more 3 object types. xml format produced legacy application , can't changed.
should expect further trouble because of using xsl transfer xml structure none xml output?
one way check preceding sibling see if exists , active , if insert ,. have edited template reflect this, write function pass node to, make life easier instead of repeating template each sibling.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:xs="http://www.w3.org/2001/xmlschema" xmlns:func="http://example.com/function" exclude-result-prefixes="xs" version="2.0"> <xsl:output encoding="utf-8" indent="yes" method="xml"/> <xsl:template match="/list"> [ <xsl:sequence select="func:processing(type_a)"/> <xsl:sequence select="func:processing(type_b)"/> <xsl:sequence select="func:processing(type_c)"/> ] </xsl:template> <xsl:function name="func:processing"> <xsl:param name="type"/> <xsl:for-each select="$type"> <xsl:if test="active != 0"> { "type": <xsl:value-of select="local-name()" />, "data": <xsl:value-of select="data_a" /> } <xsl:if test="following-sibling::*[1] , following-sibling::*[1]/active!=0"> , </xsl:if> </xsl:if> </xsl:for-each> </xsl:function> </xsl:stylesheet>
Comments
Post a Comment