我的要求如下
如果任何复杂元素只包含文本,则相应的元素属性将转换为元素到父级。
如果任何复杂元素包含子元素,则相应的元素属性将转换为元素到相同的元素级别。
此转换希望使用xslt逻辑来实现。
输入XML
<root>
<food name="desert">butter scotch</food>
<special type="nonveg">
<name>chicken</name>
</special>
</root>输出XML
<root>
<food>butter scotch</food>
<name>desert</name>
<special>
<type>nonveg</type>
<name>chicken</name>
</special>
</root>发布于 2015-11-05 22:53:47
从身份转换开始..。
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>对于“如果任何复杂元素只包含文本,则相应的元素属性转换为元素到父级”的规则,可以使用以下模板(这里我忽略注释和处理-instuctions,只检查元素没有子元素)。
<xsl:template match="*[not(*)][@*]">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
<xsl:apply-templates select="@*" mode="toelement"/>
</xsl:template>带有模式"toelement“的模板将将属性转换为一个元素。(另一条规则将重复使用)。
<xsl:template match="@*" mode="toelement">
<xsl:element name="{local-name()}">
<xsl:value-of select="." />
</xsl:element>
</xsl:template>对于规则“如果任何复杂元素包含子元素,那么相应的元素属性将转换为元素到相同的元素级别。”然后您就可以直接匹配该属性:
<xsl:template match="*[*]/@*">
<xsl:apply-templates select="." mode="toelement"/>
</xsl:template>试试这个XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="*[*]/@*">
<xsl:apply-templates select="." mode="toelement"/>
</xsl:template>
<xsl:template match="*[not(*)][@*]">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
<xsl:apply-templates select="@*" mode="toelement"/>
</xsl:template>
<xsl:template match="@*" mode="toelement">
<xsl:element name="{local-name()}">
<xsl:value-of select="." />
</xsl:element>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/33556040
复制相似问题