How to replace a tag in xml document with xslt

S

sandls816

Hi, I am quite new to xsl, so maybe there is a pretty easy solution to
this, but I couldn't find a solution anywhere.
Basically I am trying to replace a pattern of tags with other tag. For
example if my xml looks like this:

<a>
<b>
<c>
<c>some text</c>
</c>
</b>
<a>

And I want to replace <c><c> with <d> so my output would be
<a>
<b>
<d>some text</d>
</b>
</a>

The problem is that I don't know an absolute path to c/c it could be
anything, I just want to match on <c><c> no matter how far down it is.
Can this be done with xslt.
Thank you in advance
 
L

Lars Kellogg-Stedman

The problem is that I don't know an absolute path to c/c it could be
anything, I just want to match on <c><c> no matter how far down it is.
Can this be done with xslt.

This isn't heavily tested, but it might get you started in the right
direction. Someone here in the group with more XSL experience can
probably provide a better solution:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<!-- This matches <c> elements that are parents of another <c>
element, and replaces them with a <d> element containing the text
nodes of the child <c> element. -->
<xsl:template match="c[child::c]">
<d><xsl:value-of select="c/text()"/></d>
</xsl:template>

<!-- This matches everything else and just copies it to
the output. -->
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

-- Lars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top