Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading