xsl-list
[Top] [All Lists]

Re: [xsl] Noobie: normalize <b><a>...</a></b> to <a><b>...</b></a>

2010-02-18 12:13:07
I'm converting a non-XML data-dump into XML,

If it's really non-XML data, then XSLT can't help you. I presume
(since you're asking here), that you've munged it into XML somehow.

and the document contains examples of both
   <a><b>...</b></a>
and
   <b><a>...</a></b>
which (in this document) are equivalent. I'd like to use XSLT to
convert all examples of the latter to the former, with the
following caveats:
 1.  <b> can contain mixed text, in which case nothing should be changed.
 2.  <b><a>...</a></b> should be changed to <a><b>...</b></a> only if  
      the <a>...</a> element is the unique child node of <b>...</b>
How can I do this?

I am sure others can provide better methods, but I *think* the
following will do what you ask:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
version="1.0">
  
  <xsl:template match="/">
    <xsl:apply-templates select="node()"/>
  </xsl:template>
  
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="b[not(text())][a][not(*[2])]">
    <a><b><xsl:apply-templates select="a" mode="slurp"/></b></a>
  </xsl:template>
  
  <xsl:template match="a" mode="slurp">
    <xsl:apply-templates/>
  </xsl:template>
  
</xsl:stylesheet>

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--