Xslt:将属性值设置为元素名称

时间:2014-12-11 15:19:37

标签: xml xslt

我有这个xml文件:

<a>
    <x>
        text
    </x>
</a>

我需要以此结束:

<root>
    <a>
        <child name="x" />
    </a>
</root>

其实我写过:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" >
    <xsl:output method="html"/>
    <xsl:template match="/*">
        <xsl:element name="root">
            <xsl:element name="{name()}">
                <xsl:apply-templates select="*"/>
            </xsl:element>
        </xsl:element>
    </xsl:template>
    <xsl:template match="*">
        <xsl:element name="child" />
        <xsl:apply-templates select="*"/>
    </xsl:template>
</xsl:stylesheet>

给了我:

<root>
    <a>
        <child></child>
    </a>
</root>

我找到了use-attribute-sets,但似乎我无法给它输入。还有一种方法可以从<child><child>转换为<child/>(我知道它们是相同的)吗?

2 个答案:

答案 0 :(得分:3)

这将适用于您的抽象示例(在关闭根元素之后!)。如果你真正需要的是另一个问题......

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:template match="/*">
    <root>
        <xsl:copy>
            <xsl:apply-templates select="*"/>
        </xsl:copy>
    </root>
</xsl:template>

<xsl:template match="*">
    <child name="{local-name()}" />
</xsl:template>

</xsl:stylesheet>

答案 1 :(得分:0)

你可以运行这样的东西:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/*">
        <root>
            <xsl:element name="{name()}">
                <xsl:apply-templates select="*" />
            </xsl:element>
        </root>
    </xsl:template>

    <xsl:template match="*">
        <child>
            <xsl:attribute name="name">
                <xsl:value-of select="name()" />
            </xsl:attribute>
            <xsl:apply-templates select="*" />
        </child>
    </xsl:template>
</xsl:stylesheet>

You can see it working on xsltcake here

相关问题