Home > other >  how to add attribute to a parent when the text in the child match with XSLT 1.0
how to add attribute to a parent when the text in the child match with XSLT 1.0

Time:07-26

Im trying to add an attribute into a parent, when the text in a child node match, I have this input :

<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>

And when the attribute color = red, I need to add ready="yes" into TN, so I would have something like this :

<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>

Im trying this XSLT, but It add the attribute in the wrong place, because it add the attribute in the child tag color :

<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>

CodePudding user response:

Put the step from TN to color in the condition (in the square brackets):

<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>
  • Related