然后XSL复制替换属性

时间:2017-01-27 11:16:32

标签: xml xslt xslt-1.0

Input.xml中

 <human gender="male" nationality="american">
    <property>blank</property>
 </human>

(所需)OUTPUT.xml

 <human gender="male" nationality="american">
    <property>blank</property>
 </human>
 <person gender="female" nationality="british">
    <property>blank</property>
 </person>

大家好,以上是我想要的转变。 到目前为止,我有以下xsl:

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

但我如何更换属性值 我尝试使用xsl:选择但没有运气

1 个答案:

答案 0 :(得分:1)

您的样式表很接近,它只是缺少与您的其他模板不匹配的节点匹配的模板,因此它们不会被built-in templates of XSLT选中。

对于我选择引入模式的属性的转换,以便某些模板仅在您想要更改属性值的第二种情况下匹配。

以下样式表

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="human">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
    <person>
        <!-- mode is used to separate this case from the other where things are copied unchanged -->
        <xsl:apply-templates select="node()|@*" mode="other" />
    </person>   
</xsl:template>

<!-- templates for normal mode -->

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

<!-- templates for "other" mode -->

<xsl:template match="@gender" mode="other">
    <xsl:attribute name="gender">
        <xsl:if test=". = 'male'">female</xsl:if>
        <xsl:if test=". = 'female'">male</xsl:if>
    </xsl:attribute>
</xsl:template>

<xsl:template match="@nationality" mode="other">
    <xsl:attribute name="nationality">
        <xsl:if test=". = 'american'">british</xsl:if>
        <xsl:if test=". = 'british'">american</xsl:if>
    </xsl:attribute>
</xsl:template>

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

</xsl:stylesheet>

应用于此输入时:

<human gender="male" nationality="american">
    <property>blank</property>
</human>

给出以下结果:

<?xml version="1.0" encoding="UTF-8"?>
<human gender="male" nationality="american">
    <property>blank</property>
</human>
<person gender="female" nationality="british">
    <property>blank</property>
</person>