基于元素值类型的xml的XSLT转换



我想创建XSLT模式来转换我的xml记录。下面是一个传入xml 的示例

<Target>
<name1>AMRXQUAL</name1>
<name2>0</name2>
<name3>217</name3>
<name4>72</name4>
</Target>

这是xslt转换后的预期输出:

<Target>
<string_fields>
<name1>AMRXQUAL</name1>
</string_fields>
<int_fields>
<name2>0</name2>
<name3>217</name3>
<name4>72</name4>
</int_fields>
</Target>

其思想是检查Target中每个元素的类型,然后将其移动到根级别上的相应元素。如果元素类型是integer,我们将其移动到int_fields,如果元素是string,我们将它移动到string_fields等等。提前谢谢!

使用castable as,您可以检查类型,然后编写一个返回所需类型前缀的函数,并通过以下方式在组中使用:

<xsl:function name="mf:get-type" as="xs:string">
<xsl:param name="input"/>
<xsl:sequence
select="if ($input castable as xs:integer)
then 'int'
else if ($input castable as xs:decimal)
then 'dec'
else if ($input castable as xs:boolean)
then 'boolean'
else 'string'"/>
</xsl:function>
<xsl:template match="Target">
<xsl:copy>
<xsl:for-each-group select="*" group-by="mf:get-type(.)">
<xsl:element name="{current-grouping-key()}_fields">
<xsl:copy-of select="current-group()"/>
</xsl:element>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>

试试这个

<xsl:template match="Target">
<xsl:copy>
<xsl:for-each-group select="*" group-adjacent="substring(local-name(), 1, 1)">
<xsl:choose>
<xsl:when test="current-grouping-key() = 's'">
<string_fields>
<xsl:apply-templates select="current-group()"/>
</string_fields>
</xsl:when>
<xsl:when test="current-grouping-key() = 'i'">
<int_fields>
<xsl:apply-templates select="current-group()"/>
</int_fields>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>

请参阅转换https://xsltfiddle.liberty-development.net/6q1SDjN

最新更新