XSLT 1.0场景下按规则为ProductData添加<Status>节点的实现求助
XSLT 1.0 实现按优先级为指定ProductData添加Status节点
核心思路
利用XSLT 1.0的模板匹配与条件判断,先按优先级确定需要添加Status节点的目标ProductData,再对目标节点追加节点,其余节点保持原样。核心是通过<xsl:choose>按规则优先级锁定目标ID,避免全局变量标记的局限性。
完整实现代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 身份转换模板:默认复制所有节点与属性 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 专门处理Product节点,按规则筛选目标ProductData --> <xsl:template match="Product"> <xsl:copy> <!-- 按优先级确定要添加Status的目标ID --> <xsl:variable name="targetId"> <xsl:choose> <!-- 规则1:ID3存在且Number>10,优先选ID3 --> <xsl:when test="ProductData[@ID='ID3' and Number > 10]">ID3</xsl:when> <!-- 规则2:ID3无效,且ID1、ID2均存在且有效,选ID2 --> <xsl:when test="not(ProductData[@ID='ID3' and Number > 10]) and ProductData[@ID='ID1' and Number > 10] and ProductData[@ID='ID2' and Number > 10]">ID2</xsl:when> <!-- 规则3:ID2、ID3均无效,ID1有效,选ID1 --> <xsl:when test="not(ProductData[@ID='ID2' and Number > 10]) and not(ProductData[@ID='ID3' and Number > 10]) and ProductData[@ID='ID1' and Number > 10]">ID1</xsl:when> <!-- 无符合条件的节点,空值 --> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:variable> <!-- 遍历所有ProductData,为目标节点追加Status --> <xsl:for-each select="ProductData"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <xsl:if test="@ID = $targetId"> <Status>Done</Status> </xsl:if> </xsl:copy> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet>
规则对应逻辑说明
- 规则1处理:直接判断
Product下是否存在@ID='ID3'且Number>10的ProductData,存在则将目标ID设为ID3。 - 规则2处理:先通过
not()判断ID3无效(不存在或Number≤10),同时验证ID1、ID2均满足有效条件,将目标ID设为ID2。 - 规则3处理:确认ID2、ID3均无效,且ID1有效,将目标ID设为
ID1。
测试示例
测试输入(符合规则2)
<Product> <ProductData ID="ID1"> <Number>15</Number> </ProductData> <ProductData ID="ID2"> <Number>13</Number> </ProductData> <ProductData ID="ID3"> <Number>8</Number> </ProductData> </Product>
输出结果
<Product> <ProductData ID="ID1"> <Number>15</Number> </ProductData> <ProductData ID="ID2"> <Number>13</Number> <Status>Done</Status> </ProductData> <ProductData ID="ID3"> <Number>8</Number> </ProductData> </Product>
内容的提问来源于stack exchange,提问作者User_Earth_005
相关产品推荐
相关产品推荐

