首页 > 解决方案 > 如何从 XSLT 中具有两个根节点的 XML 中获取数据

问题描述

这是我拥有的 XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <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>
</catalog>
<catalog>
<cd>
    <title>Stop</title>
    <artist>Sam Brown</artist>
    <country>UK</country>
    <company>A and M</company>
    <price>8.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Bridge of Spies</title>
    <artist>T`Pau</artist>
    <country>UK</country>
    <company>Siren</company>
    <price>7.90</price>
    <year>1987</year>
  </cd>
</catalog>

以下是我试图从两个根节点获取数据的 XSLT:

<?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>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/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>

它只返回 2 条记录。我需要获得 4 条记录。我应该在 select 语句中写什么。我试过反斜杠,星号。没用。请帮忙!

或者如何将两个根节点包含在 xslt 中的单个根节点中?

实际输出:

My CD Collection
Title                   Artist
------------------------------------
Empire Burlesque        Bob Dylan
Hide your heart         Bonnie Tyler

期望的输出:

My CD Collection
Title                   Artist
------------------------------------
Empire Burlesque        Bob Dylan
Hide your heart         Bonnie Tyler
Stop                    Sam Brown
Bridge of Spies         T`Pau

你可以试试这个链接来测试。请不要忘记复制粘贴上面提到的xml: https ://www.w3schools.com/xml/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog_ex3

标签: xmlxsltedg

解决方案


推荐阅读