xsl-list
[Top] [All Lists]

RE: XML to XML

2004-05-20 13:01:55
-----Original Message-----
From: Norma Yeazell [mailto:Nyeazell(_at_)oneil(_dot_)com]


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[(_at_)type='elem'][(_at_)from=name(current())]">
      <xsl:element 
name="{$vmap[(_at_)type='elem'][(_at_)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[(_at_)type='attr'][(_at_)from=name(current())]">
      <xsl:attribute
name="{$vmap[(_at_)type='attr'][(_at_)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



<Prev in Thread] Current Thread [Next in Thread>