使用xslt将后续元素作为xml中的属性

时间:2017-06-19 13:43:47

标签: java xml xslt xslt-1.0

如果后续元素使用XSLT包含前面的元素名称,

需要帮助将后续元素作为前一元素的属性。

对于以下示例,< emp _id>包含前面的元素名称,因此需要将此元素作为属性转换为元素。你可以帮忙吗?我尝试在xslt中使用后续函数但不能正常工作。提前谢谢。

示例XML:

<root>
    <emp>test</emp>
    <emp_id>1234</emp_id>
    <college>something</college>
</root>

期待:

<root>
    <emp id="1234">test</emp>
    <college>something</college>
</root>

1 个答案:

答案 0 :(得分:0)

In the given example, you could do:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="following-sibling::*[starts-with(name(), name(current()))]" mode="attr"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="attr">
    <xsl:attribute name="{substring-after(name(), '_')}">
        <xsl:value-of select="." />
    </xsl:attribute>
</xsl:template>

<xsl:template match="*[preceding-sibling::*[name()=substring-before(name(current()), '_')]]"/>

</xsl:stylesheet>

to achieve the expected result.


There is probably a more elegant way, but we need to have some more rules, not just a single example.


Added:

Assuming that every element whose name contains a _ has a "parent" element whose attribute it should become, you can start by applying templates to only the "parent" elements (i.e. elements whose name does not contain a '_').

Then use a key to collect the "child" elements that need to be converted to attributes.

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="atr" match="*" use="substring-before(name(), '_')" />

<xsl:template match="/root">
    <xsl:copy>
        <xsl:apply-templates select="*[not(contains(name(), '_'))]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:for-each select="key('atr', name())">
            <xsl:attribute name="{substring-after(name(), '_')}">
                <xsl:value-of select="." />
            </xsl:attribute>
        </xsl:for-each>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>