首页 > 解决方案 > XSLT 标记插入

问题描述

我有一个多级 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>

标签: xsltinsertattributes

解决方案


总是落入 xsl:否则

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

如果您可以拥有多个,则需要从上下文中Employee计算 的值- 例如:ScenarioEmployee

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>

推荐阅读