[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

RE: [xsl] XML to XML


Subject: RE: [xsl] XML to XML
From: "Andreas L. Delmelle" <a_l.delmelle@xxxxxxxxxx>
Date: Thu, 20 May 2004 22:01:55 +0200

> -----Original Message-----
> From: Norma Yeazell [mailto:Nyeazell@xxxxxxxxx]
>

Hi,

> I want to transform XML  to XML using different elements. I thought I
> could do this but have been unable to find any samples to get me
> started. Can anyone help me out with this?
>
> For instance the original XML has an element <maintain> and the new XML
> should be <maintwp> and many more.
>

This can be done with no more than:

<xsl:template match="maintain">
  <maintwp>
    <xsl:apply-templates select="@* | node()" />
  </maintwp>
</xsl:template>

A simple copy template for all nodes for which you want to leave the names
unchanged, and one similar to the above for the others.

If you're looking more for a general solution, have an XML map of the
element names in an external file, or in another namespace in your
stylesheet, bind this map to a variable, and create an element/attribute
with the mapped name or simply a copy.

Roughly something like:

<xsl:stylesheet ... xmlns:map="map:namespace">
...
<map:mapping type="elem" from="maintain" to="maintwp" />
<map:mapping type="attr" from="att-one" to="att-two" />
...
<xsl:variable name="vmap" select="document('')/*/map:mapping" />
...
<xsl:template match="*">
  <xsl:choose>
    <!-- if there is a mapping, use it -->
    <xsl:when test="$vmap[@type='elem'][@from=name(current())]">
      <xsl:element name="{$vmap[@type='elem'][@from=name(current())]/@to}">
        <xsl:apply-templates select="@* | node()" />
      </xsl:element>
    </xsl:when>
    <!-- else, just copy and continue -->
    <xsl:otherwise>
      <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
      </xsl:copy>
    </xsl:otherwise>
  </xsl:when>
</xsl:template>

<xsl:template match="@*">
  <xsl:choose>
    <xsl:when test="$vmap[@type='attr'][@from=name(current())]">
      <xsl:attribute
name="{$vmap[@type='attr'][@from=name(current())]/@to}">
        <xsl:value-of select="." />
      </xsl:attribute>
    </xsl:when>
    <xsl:otherwise>
      <xsl:copy-of select="." />
    </xsl:otherwise>
  </xsl:when>
</xsl:template>

</xsl:stylesheet>

HTH!

Greetz,

Andreas


Current Thread
Keywords
xml