XSLT替换一个部分
问题描述:
我想用XSLT替换XML中的一个部分。XSLT替换一个部分
输入:
<data>
<entry>
<id>1</id>
<propertyA>10</propertyA>
<propertyB>20</propertyB>
</entry>
<entry>
<id>2</id>
<propertyA>8</propertyA>
<propertyB>12</propertyB>
</entry>
</data>
预期输出:
<data>
<entry>
<id>1</id>
<propertyA>15</propertyA>
<propertyB>8</propertyB>
</entry>
<entry>
<id>2</id>
<propertyA>8</propertyA>
<propertyB>12</propertyB>
</entry>
</data>
我打算做到这一点使用XSLT副本的所有节点,但跳过目标条目&产生他们在的地方具有新的价值。
作为第一步,我编写了一个XSLT来跳过目标条目。
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="/data/entry">
<xsl:choose>
<xsl:when test="id=$replaceId"></xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
但是,当$ replaceId = 1 - 缺少入口元素时,我收到以下输出。我明白我的模板匹配entry
中的xsl:apply-templates
正在造成这种情况。但是,我不知道如何解决这个问题。在网上搜索一小时并没有帮助我。我相信,所以人们可以帮助我。
<data>
<id>2</id>
<propertyA>8</propertyA>
<propertyB>12</propertyB>
</data>
答
的entry
元素从输出中缺少的,因为你不把它复制到输出。此外,在该情况下“时”的条件是:
<xsl:when test="id=$replaceId"></xsl:when>
这个entry
元素的子节点都不会被处理。
一般来说,最好是利用单独的模板而不是依靠xsl:choose
。元素propertyA
和propertyB
是您真正想要修改的元素 - 所以最好编写与其直接匹配的模板。
样式表
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="replaceID" select="'2'"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="propertyA[parent::entry/id = $replaceID]">
<xsl:copy>
<xsl:value-of select="15"/>
</xsl:copy>
</xsl:template>
<xsl:template match="propertyB[parent::entry/id = $replaceID]">
<xsl:copy>
<xsl:value-of select="8"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出
<?xml version="1.0" encoding="UTF-8"?>
<data>
<entry>
<id>1</id>
<propertyA>15</propertyA>
<propertyB>8</propertyB>
</entry>
<entry>
<id>2</id>
<propertyA>8</propertyA>
<propertyB>12</propertyB>
</entry>
</data>