xml - 为 Atom 提要创建 XSL

标签 xml xslt

我正在创建一个小的自定义 XSL 文件来呈现 RSS 提要。内容基本,如下。除非源 XML 在提要定义中包含行 'xmlns="http://www.w3.org/2005/Atom"' ,否则此操作完美无缺。我该如何解决这个问题?我对命名空间不够熟悉,不知道如何处理这种情况。

<?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>

最佳答案

您将命名空间声明放入 XSLT,如下所示:

<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>

请注意,ATOM namespace 是使用前缀 atom: 注册的并在整个样式表中的所有 XPath 中使用。我用过 exclude-result-prefixes确保 atom:不会出现在生成的文档中。

另请注意,我替换了您的 <xsl:for-each>与模板。您也应该尽量避免使用 for-each,而使用模板。

disable-output-escaping="yes"的使用与 XHTML 一起使用时有些危险 - 除非您绝对肯定 summary 的内容也是格式良好的 XHTML。

关于xml - 为 Atom 提要创建 XSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974366/

相关文章:

java - 根据选择的 Spinner 项目调用不同的方法 - Android

Java - 将 JSON 转换为 XML 并保持属性

xml - 如何使用 Xpath 访问此 xml 节点中的数据 (CDATA)?

java - 如何反转 DSpace 中项目 View 的显示顺序?

java - 如何通过SAX获取嵌套xml对象的数据

xml - 如何独立于区域设置从 XML 文件中正确读取浮点值?

javascript - 将 xsl 变量传递给 javascript 函数

xml - 如何使用 XSL 将 XML 文件转换为 SVG?

xslt - 如何使用 XSLT 用它们的转义变体替换某些字符?

xslt - XSL 模板匹配语法