Search code examples
xmlxsltxslt-1.0xslt-2.0

use xslt to create tag in in parent node


Suppose I have an XML document something like this (note that for my purposes, the order the tags appear in the final document doesn't matter, in case that makes a difference; we're just using XML as a fancy key/value pair contraption)

<MyRoot>
 various tags here I don't care about at the moment
 <child><GoldenTag>1234</GoldenTag></child>
</MyRoot>

Note that the value of GoldenTag is not always 1234; this was just for illustration. Now, I want to create a SilverTag that is a (direct) child of MyRoot, whose value is the same as GoldenTag, assuming that GoldenTag exists and various other conditions are met.

I see no good way to do this, because if I use template mach='GoldenTag' then the contents of the template ends up inside the child tag which is not where I want it.


Solution

  • Any match on MyRoot can of course also include conditions on other elements e.g.

    <xsl:template match="MyRoot[child/GoldenTag and your-other-conditions]">
      <xsl:copy>
          <xsl:apply-templates/>
          <SilverTag><xsl:value-of select="child/GoldenTag"/></SilverTag>
      </xsl:copy>
    </xsl:template>