简体   繁体   English

为什么我的 XSLT 输出中有多余的文本?

[英]Why the extra text in my XSLT output?

Below is an example of the XML and XSLT:下面是 XML 和 XSLT 的示例:

XML : XML :

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <count>5</count>
  <idx>10</idx>
  <cds>
    <cd>
      <title>Empire Burlesque</title>
      <artist>Bob Dylan</artist>
      <country>USA</country>
      <company>Columbia</company>
      <price>10.90</price>
      <year>1985</year>
    </cd>
    <cd>
      <title>Hide your heart</title>
      <artist>Bonnie Tyler</artist>
      <country>UK</country>
      <company>CBS Records</company>
      <price>9.90</price>
      <year>1988</year>
    </cd>
  </cds>
</catalog>

XSLT : XSLT :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="html" omit-xml-declaration="yes" standalone="yes" />
    <xsl:template match="/catalog/cds">
      <html>
      <body>
      <h2>My CD Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th style="text-align:left">Title</th>
            <th style="text-align:left">Artist</th>
          </tr>
          <xsl:for-each select="cd">
          <tr>
            <td><xsl:value-of select="title"/></td>
            <td><xsl:value-of select="artist"/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
      </html>
    </xsl:template>
</xsl:stylesheet>

Question : Why is it that when transforming the given XML document the content of the elements count and idx is being printed out before the table all the time?问题:为什么在转换给定的 XML 文档时,元素countidx内容总是在表格之前打印出来?

The XSLT built-in templates (documentation for XSLT2 and XSLT3 ) are doing that. XSLT内置模板XSLT2XSLT3 的文档)正在这样做。 Specifically:具体来说:

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

You can override, or simply change your template from matching cds您可以覆盖或简单地从匹配的cds更改模板

<xsl:template match="/catalog/cds">

to matching / :匹配/

<xsl:template match="/">

and the spurious text node output will be avoided.并且将避免虚假文本节点输出。

您编写的唯一模板匹配<xsl:template match="/catalog/cds"> ,但是处理从文档节点开始,在您的情况下使用内置模板https://www.w3.org/TR /xslt20/#built-in-rule ,因此您必须编写匹配//catalog的模板,否则您必须确保编写的模板不会为您不想生成的元素输出任何内容输出。

另一种选择是使用不执行任何操作的版本覆盖样式表中的内置模板规则:

<xsl:template match="text()|@*" mode="#all"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM