如何用XSLT 1.0在子节点文本匹配时为父节点添加属性
问题:为包含red子节点的添加ready属性
需要实现的逻辑:当ready="yes"属性。
输入XML
<CS> <CN name="PICTURE 1"> <TN name="L_1"> <color>red</color> <ptCN>IN4</ptCN> <ID>10</ID> </TN> </CN> <CN name="PICTURE 2"> <TN name="L_2"> <color>blue</color> <ptCN>IN3</ptCN> <ID>20</ID> </TN> </CN> <CS>
期望输出XML
<CS> <CN name="PICTURE 1" > <TN name="L_1" ready="yes"> <color>red</color> <ptCN>IN4</ptCN> <ID>10</ID> </TN> </CN> <CN name="PICTURE 2"> <TN name="L_2"> <color>blue</color> <ptCN>IN3</ptCN> <ID>20</ID> </TN> </CN> <CS>
原错误代码
原代码错误地将属性添加到了
<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"/> <xsl:strip-space elements="*"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match='//TN/color[text()="red"]'> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:attribute name="ready">yes</xsl:attribute> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
修正后的XSLT代码
<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"/> <xsl:strip-space elements="*"/> <!-- 身份模板,复制所有节点和属性 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配包含red子节点的TN元素 --> <xsl:template match="TN[color/text()='red']"> <xsl:copy> <!-- 复制原有的所有属性 --> <xsl:apply-templates select="@*"/> <!-- 添加ready属性 --> <xsl:attribute name="ready">yes</xsl:attribute> <!-- 处理子节点 --> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
修改说明
- 原模板匹配的是
<color>节点,导致属性加错位置,现在改为直接匹配包含文本为red的子节点的 ,即节点 TN[color/text()='red']。 - 在匹配
的模板中,先复制原有属性,再添加 ready="yes",最后处理子节点,保证的结构和内容完整。
内容的提问来源于stack exchange,提问作者JC44
相关产品推荐
相关产品推荐

