Skunkwaffle
Skunkwaffle

Reputation: 624

XSLT finding links inside tags in XML documents

Is there a way to have an xsl stylesheet recognize when a link appears inside a tag in an xml document and turn it into a working link?

Example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="guys.xsl"?>

<people>
   <person>
      <name>Guy 1</name>
      <bio>Guy 1 is a guy.</bio>
   </person>

   <person>
      <name>Guy 2</name>
      <bio>Guy 2 is from <a href="http://www.example.com">somewhere</a>.</bio>
   </person>
</people>

Guy 1's bio should just appear as regular text, Guy 2's bio should have a working link in it.

Upvotes: 1

Views: 203

Answers (2)

Wheeyls
Wheeyls

Reputation: 1012

This will work right out of the box if you are trying to display this in html format:

<html>
<body>
  <xsl:for-each select="people/person">
     <div>
       <xsl:value-of select="name"/>
     </div>
     <div>
       <xsl:copy-of select="bio"/>
     </div>
  </xsl:for-each>
</body>
</html>

EDIT: changed value-of to copy-of. See this discussion: How do I preserve markup tags?

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

Is there a way to have an xsl stylesheet recognize when a link appears inside a tag in an xml document and turn it into a working link?

Yes. This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
   <table border="1">
     <xsl:apply-templates/>
   </table>
 </xsl:template>

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

 <xsl:template match="person/*">
   <td><xsl:copy-of select="node()"/></td>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<people>
   <person>
      <name>Guy 1</name>
      <bio>Guy 1 is a guy.</bio>
   </person>

   <person>
      <name>Guy 2</name>
      <bio>Guy 2 is from <a href="http://www.example.com">somewhere</a>.</bio>
   </person>
</people>

produces the wanted result:

<table border="1">
   <tr>
      <td>Guy 1</td>
      <td>Guy 1 is a guy.</td>
   </tr>

   <tr>
      <td>Guy 2</td>
      <td>Guy 2 is from <a href="http://www.example.com">somewhere</a>.</td>
   </tr>
</table>

Upvotes: 3

Related Questions