如何使用XSLT去除最外面的包装?(How do I remove the outermost wr

2019-09-30 05:46发布

示例XML是:

<a amp="a"><b><c>this is the text</c></b></a>

需要转换到:

<a amp="a"><c>this is the text</c></a>

Answer 1:

溶液#1:轻微改进的smaccoun溶液将保留的任何属性c元件(没有必要例如XML):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="c">
        <xsl:copy-of select="." />
    </xsl:template>
</xsl:stylesheet>

解决方案#2,充分利用了另一种选择内置模板规则 ,适用模板的所有元素,并复制text()

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template for the c element, it's decendant nodes, 
        and attributes (which will only get applied from c or 
        descendant elements)-->
    <xsl:template match="@*|c//node()|c">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

溶液#3:改性恒等变换:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template, copies all content by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--don't generate content for these matched elements, 
        just apply-templates to it's children-->
    <xsl:template match="a|b">
        <xsl:apply-templates/>
    </xsl:template>     
</xsl:stylesheet>

解决方案#4如果你知道你想要什么,只是从根节点上的匹配复制

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:copy-of select="a/b/c" />
    </xsl:template>
</xsl:stylesheet>

如果您想直接删除<b>从您的输入元素,然后修改的身份变换应该与模板匹配使用<b>元素只是简单的应用模板,它的孩子。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template, copies all content by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--don't generate content for the <b>, just apply-templates to it's children-->
    <xsl:template match="b">
        <xsl:apply-templates/>
    </xsl:template>     
</xsl:stylesheet>


Answer 2:

应用该模板<c>然后只用一个副本的设计模式。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match='c'>
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>


文章来源: How do I remove the outermost wrappers using xslt?
标签: xml xslt