XSLT删除父元素而不影响子元素

时间:2018-10-29 13:03:40

标签: xml xslt

下面是我的inputxml:

public selectAllItems() {
  this.jsonObj = this.jsonObj.map(item => {
    item.allTobuliItem = this.allTobuli;
    return item;
  });
}

下面是我的xslt:

<?xml version="1.0" encoding="UTF-8"?>
<tag:dataList xmlns:tag="http://www.example.com/tempuri">
<Item>Data1</Item>
<Item>Data2</Item>
</tag:dataList>

我从xslt得到的响应是:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tag="http://www.example.com/tempuri">
<xsl:output indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Item">
        <xsl:element name="tag:dataRef">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
</xsl:template>
</xsl:stylesheet>

但是我想得到的答复是:

<?xml version="1.0" encoding="UTF-8"?>
<tag:dataList xmlns:tag="http://www.example.com/tempuri">
<tag:dataRef>Data1</tag:dataRef>
<tag:dataRef>Data2</tag:dataRef>
</tag:dataList>

如何使用xslt实现此目的?

期待您的解决方案。 预先感谢。

1 个答案:

答案 0 :(得分:2)

您没有在匹配模板中创建父元素。对于所需的输出,您需要这样做:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tag="http://www.example.com/tempuri" version="1.0">

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
        <root>
            <xsl:apply-templates/>
        </root>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="tag:dataList">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="Item">
        <tag:dataList xmlns:tag="http://www.example.com/tempuri">
            <xsl:element name="tag:dataRef">
                <xsl:apply-templates select="@*|node()"/>
            </xsl:element>
        </tag:dataList>
    </xsl:template>

</xsl:stylesheet>

注意::这里您有多个父元素,因此您需要按照XML标准将所有元素包装在一个根元素中。