设置节点以在同一父节点下继承特定节点

时间:2014-09-03 07:53:54

标签: xml xslt

我有以下XSLT文件,它在Parent下设置SpecialChild。

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

    <xsl:template match="GrandParent">
        <xsl:element name="tns:{name()}" namespace="http://www.test.com/ComBase/eom/1.0/">
            <xsl:copy-of select="namespace::*"/>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="Parent">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
            <xsl:if test = "count(SpecialChild) > 0">
                <SpecialChild>
                    <xsl:apply-templates select="SpecialChild/*"/>
                </SpecialChild>
            </xsl:if>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="SpecialChild"/>

    <xsl:template match="node()|@*">
        <xsl:if test="normalize-space(string(.)) != ''">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

但是,我希望它在OtherChild节点下,而不是总是位于底部。

预期:

<Parent>
    <OtherChild></OtherChild>
    <SpecialChild></SpecialChild>
    <OtherInfo></OtherInfo>
</Parent>

实际值:

<Parent>
    <OtherChild></OtherChild>
    <OtherInfo></OtherInfo>
    <SpecialChild></SpecialChild>
</Parent>

我应该对XSLT进行哪些更改才能实现?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

以这种方式尝试(未经测试,因为没有输入来测试它):

XSLT 1.0

<?xml version="1.0" encoding="UTF-8"?>
<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="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="GrandParent">
    <xsl:element name="tns:{name()}" namespace="http://www.test.com/ComBase/eom/1.0/">
        <xsl:copy-of select="namespace::*"/>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
</xsl:template>

<xsl:template match="Parent">
    <xsl:copy>
        <xsl:apply-templates select="@*|OtherChild"/>
        <xsl:if test="SpecialChild">
            <SpecialChild>
                <xsl:apply-templates select="SpecialChild/*"/>
            </SpecialChild>
        </xsl:if>
        <xsl:apply-templates select="*[not(self::OtherChild or self::SpecialChild)]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="SpecialChild"/>

</xsl:stylesheet>

注意:
您的第一个和最后一个模板是冲突的;我删除了最后一个。