Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating XSL for Atom feed

Tags:

xml

xslt

I'm creating a small custom XSL file to render an RSS feed. The contents are basic, as follows. This works flawlessly except when the source XML contains the line 'xmlns="http://www.w3.org/2005/Atom"' in the feed definition. How do I address this? I'm not familiar enough with namespaces to know how to account this case.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/" >
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
  <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
  <xsl:for-each select="feed/entry">
      <div style="background-color:teal;color:white;padding:4px">
        <span style="font-weight:bold"><xsl:value-of select="title"/></span> - <xsl:value-of select="author"/>
      </div>
      <div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
        <b><xsl:value-of select="published" /> </b>
        <xsl:value-of select="summary"  disable-output-escaping="yes" />
      </div>
    </xsl:for-each>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>
like image 680
Tim Brigham Avatar asked Jan 23 '12 15:01

Tim Brigham


1 Answers

You put the namespace declaration into the XSLT, like this:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:atom="http://www.w3.org/2005/Atom"
  exclude-result-prefixes="atom"
>
  <xsl:template match="/">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
        <xsl:apply-templates select="atom:feed/atom:entry" />
      </body>
    </html>
  </xsl:template>

  <xsl:template match="atom:entry">
    <div style="background-color:teal;color:white;padding:4px">
      <span style="font-weight:bold">
        <xsl:value-of select="atom:title"/>
      </span>
      <xsl:text> - </xsl:text>
      <xsl:value-of select="atom:author"/>
    </div>
    <div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
      <b><xsl:value-of select="atom:published" /> </b>
      <xsl:value-of select="atom:summary"  disable-output-escaping="yes" />
    </div>
  </xsl:template>
</xsl:stylesheet>

Note that the ATOM namespace is registered with the prefix atom: and used in all XPath throughout the stylesheet. I've used exclude-result-prefixes to make sure atom: will not show up in the resulting document.

Also note that I replaced your <xsl:for-each> with a template. You should try to avoid for-each in favor of templates, as well.

The use of disable-output-escaping="yes" is somewhat dangerous in conjunction with XHTML - unless you are absolutely positive that the contents of summary is well-formed XHTML, too.

like image 79
Tomalak Avatar answered Sep 21 '22 21:09

Tomalak