RE: Converting XML <link> to HTML anchor

Subject: RE: Converting XML <link> to HTML anchor
From: Mike Brown <mbrown@xxxxxxxxxxxxx>
Date: Wed, 8 Dec 1999 20:19:15 -0700
Michael Teigman wrote:
> I have an xml like this:
> 
> <text>
>     <p>Text1</p>
>     <p>Text2 <link href="link1">label1</link></p>
>     <p><link href="link2">label2</link></p>
>     <p>Text3 <link href="link3">label3</link> text4 <link
> href="link4">label4</link> text 5</p>
> </text>
> 
> For example I want from the above:
> 
> <p>
>     <p>Text1</p>
>     <p>Text2 <a href="link1">label1</a></p>
>     <p><a href="link2">label2</a></p>
>     <p>Text3 <a href="link3">label3</a> text4 <a 
> href="link4">label4</a> text 5</p>
> </p>

Well, your nesting of <p>'s within <p>'s is invalid HTML, so I'll take the
liberty of changing the enclosing one to a <div>. These 3 templates should
handle any arbitrary nesting of text, p, and link elements in the source
tree.

<xsl:template match="text">
  <div>
     <xsl:apply-templates/>
  </div>
</xsl:template>

<xsl:template match="p">
  <p>
    <xsl:apply-templates/>
  </p>
</xsl:template>

<xsl:template match="link">
  <a href="{@href}">
    <xsl:apply-templates/>
  </a>
</xsl:template>

To help understand why they work, remember there are built-in templates:

<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>

And know that <xsl:apply-templates/>, if no select attribute is given, will
find the templates that best match each child of the current node, and will
invoke them one by one.


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread