我在系统环境中获得了以下(简化的)XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<IS_LOG>
<USER>19291</USER>
<DATE>2011-08-15</DATE>
<TIME>15:36:36</TIME>
<SYST>sy1</SYST>
<MATERIALS>
<item>
<sy>100</sy>
<mat>000000000000310000</mat>
</item>
<item>
<sy>100</sy>
<mat>000000000000491078</mat>
</item>
</MATERIALS>
</IS_LOG>
</root>
我使用的系统在运行时向我传递了一个变量,该变量未包含在上面的 XML 结构中。
我有以下 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" version="1.0">
<!-- System variable whose value I normally only get only at runtime;
for test purposes set locally -->
<xsl:variable name="SenderService" select="'AT'"/>
<xsl:template match="@*|node()">
<xsl:choose>
<xsl:when test="$SenderService='AT'">
<xsl:copy>
<xsl:apply-templates mode="AT" select="@*|node()"/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template mode="AT" match="item[mat > 000000000000299999 and mat < 000000000000399999]"/>
</xsl:stylesheet>
现在我需要复制所有元素 item
,不包括 mat
的数字范围为 300000 到 399999 且 SenderService
为 '在'。
如果要在本地测试它,我将 XSLT 中的 SenderService
更改为例如“Z”,输出看起来不错,所有项目
都被复制:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<IS_LOG>
<USER>19291</USER>
<DATE>2011-08-15</DATE>
<TIME>15:36:36</TIME>
<SYST>sy1</SYST>
<MATERIALS>
<item>
<sy>100</sy>
<mat>000000000000310000</mat>
</item>
<item>
<sy>100</sy>
<mat>000000000000491078</mat>
</item>
</MATERIALS>
</IS_LOG>
</root>
但是如果我将 SenderService
设置为“AT”,输出将如下所示:
<?xml version="1.0" encoding="UTF-8"?><root>
19291
2011-08-15
15:36:36
sy1
100
000000000000491078
</root>
正确的项目被复制,但没有标签。如何更改 XSLT?
最佳答案
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="SenderService" select="'AT'"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="item[mat > 000000000000299999 and mat < 000000000000399999]">
<xsl:if test="$SenderService != 'AT'">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
关于xml - XSLT 1.0 : copy everything except certain nodes according to value and variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7078881/