0

I have an xml of type

<A>
    <B1>
        <C1 attri= "xyz"/>
    </B1>

    <B2>
        <C2>
            <D2> replace </D2>
        </C2>
    </B2>
<A>

My task is to check the C1 attribute, and if it is "xyz", replace the text "replace" with "New Text". Any ideas?

2
  • DO you want to output exactly the same structure and have (...)<D2> New Text </D2>(...) ? Commented Jul 5, 2013 at 18:07
  • Yes, just the content text has to be replaced Commented Jul 5, 2013 at 18:09

1 Answer 1

1
<xsl:template match="D2">
  <xsl:copy>
    <xsl:choose>
      <xsl:when test="/A/B1/C1@attri = 'xyz'">
        <xsl:text>New Text</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:copy>
</xsl:template>

The rest of the stylesheet can be the identity transform.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I tried something similar to this. But then my problem got more complex when I realized that number of Node Levels between D2 and A are not fixed at 3 and could vary. So I used the ancestor Tag and // functionality to jump up as many levels as required, and it worked. But now I am faced with another problem. Not only do I have to change the text (which you showed how it can be done) without fixed number of levels (using ancestor and // for that), I also have to get rid of the A tag (<A>), if of course, my attribute matches "xyz". Any suggestion how I can achieve that?
Study the template given in the answer. You will notice that there are essentially three regions in the text of the template: the contents of the first 'when' element (evaluated when its test succeeds), the 'otherwise' element (evaluated when the test fails), and the remainder of the template (evaluated for every matching element). If you can't see how to apply that pattern to a template matching A, and adjust it to preserve, or not preserve, the A element under appropriate conditions, then you need to spend some time improving your understanding of how programs work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.