XSLT 标记插入

XSLT Tag Insert

我有一个 XML 的多级块,我的要求是为每个 Employee 块注入一个新的 Scenario 标签。新场景标签中的值可以根据事件标签中的值进行更改

来自

<Extract>
    <Header>
        <Date1>01/01/2020</Date1>
    </Header>
    <Employee>
        <Status>
            <Event>Event_1</Event>
        </Status>
    </Employee>
    <Employee>
        <Status>
            <Event>Event_2</Event>
        </Status>
    </Employee>
</Extract>

<Extract>
    <Header>
        <Date1>01/01/2020</Date1>
    </Header>
    <Employee>
        <Status>
            <Event>Event_1</Event>
        </Status>
        <Scenario>A</Scenario>
    </Employee>
    <Employee>
        <Status>
            <Event>Event_2</Event>
        </Status>
        <Scenario>B</Scenario>
    </Employee>
</Extract>

我一直在研究这个问题,我能够成功插入标签,但在添加标签之前,我希望有一个选择语句来确定标签中所需的输出。如下

<xsl:param name="to-insert"> 
    <xsl:choose>
        <xsl:when test="Employee/Status/Event = 'Event_1' ">
                <Scenairo>A</Scenairo>
        </xsl:when>
        <xsl:when test="Employee/Status/Event = 'Event_2' ">
                <Scenairo>B</Scenairo>
        </xsl:when>
        <xsl:otherwise>
            <Scenairo><xsl:value-of select="'no scenario mapped'"/></Scenairo>
        </xsl:otherwise>
    </xsl:choose>
</xsl:param>

<!-- Copy all sections of XML -->
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>

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

always falls into xsl:otherwise

否,但它仅评估第一个 Employee(在 XSLT 1.0 中)或所有员工一起(在 XSLT 2.0 中)。

如果可以有多个 Employee,则需要根据 Employee 的上下文计算 Scenario 的值 - 例如:

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"/>

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

<xsl:template match="Employee">
    <xsl:copy>
        <xsl:apply-templates/>
        <Scenario>
            <xsl:choose>
                <xsl:when test="Status/Event = 'Event_1'">A</xsl:when>
                <xsl:when test="Status/Event = 'Event_2'">B</xsl:when>
                <xsl:otherwise>no scenario mapped</xsl:otherwise>
            </xsl:choose>
        </Scenario>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>