使用XSLT模板将XML转换为HTML

时间:2017-12-20 20:41:52

标签: xml xslt xpath

有人可以帮助我使用XSLT模板将以下XML转换为HTML。

XML格式:

<content>
<para>Please click <link href="https://www.google.com">here</para> to navigate to Google search.
</content>

预期的HTML:

<p>Please click <a href="https://www.google.com">here</a> to navigate to Google search.</p>

我尝试过以下模板,不知道如何继续进行。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <p><xsl:value-of select="content/para"/><p>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

实际结果:

<p>Please click</p>

1 个答案:

答案 0 :(得分:1)

identity transform开头。这将按原样复制所有内容(元素,属性,文本,注释,处理指令)。

添加更多特定模板以覆盖标识转换或built-in template rules

的处理

示例...

XML输入(已修复为格式良好)

<content>
    <para>Please click <link href="https://www.google.com">here</link> to navigate to Google search.</para>
</content>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <!-- Identity transform -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/content">
    <html>
      <body>
        <xsl:apply-templates/>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="para">
    <p>
      <xsl:apply-templates select="@*|node()"/>
    </p>
  </xsl:template>

  <xsl:template match="link">
    <a>
      <xsl:apply-templates select="@*|node()"/>
    </a>
  </xsl:template>

</xsl:stylesheet>

<强>输出

<html>
   <body>
      <p>Please click <a href="https://www.google.com">here</a> to navigate to Google search.
      </p>
   </body>
</html>

获得good book on XSLT并首先阅读该文件也是一个好主意。

相关问题