XSL:从XML中引用的元素获取数据(ref,id)

时间:2017-07-04 08:11:33

标签: xml xslt reference

我想获取一个author-element的名称,该名称由XML文件中的book-element引用,但我还没有想出如何访问它。

下面是我的XSL代码和我的XML的样子。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/library">
<html>
  <head>
    <link rel="stylesheet" href="librarytable.css" type="text/css"/>
  </head>
  <body>
    <h2>Bibliothek</h2>
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Jahr</th>
          <th>Autor(en)</th>
        </tr>
      </thead>
      <xsl:for-each select="book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="year"/></td>
        <td><xsl:value-of select="author-ref"/></td>
        <!-- author-ref just to fill in the blank-->
      </tr>
      </xsl:for-each>
    </table>
  </body>
</html>
</xsl:template>
</xsl:stylesheet> 

这就是本书和作者在我的XML中的连接方式:

<book>
    <author-ref>T.Pratchett</author-ref>
    <title>The Colour of Magic</title>
    <year>1983</year>
</book>

<author id="T.Pratchett">
    <last-name>Pratchett</last-name>
    <first-name>Terry</first-name>
</author>

以下是它的样子,但是我想在表格单元格中使用Terry Pratchett代替T.Pratchett。

Book Table

如果有人知道如何解决这个问题,我将非常感激。 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用密钥按author属性查找id元素。

<xsl:key name="authors" match="author" use="@id" />

因此,要查找作者当前的书,你会这样做......

<xsl:value-of select="key('authors', author-ref)"/>

试试这个XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="authors" match="author" use="@id" />

<xsl:template match="/library">
<html>
  <head>
    <link rel="stylesheet" href="librarytable.css" type="text/css"/>
  </head>
  <body>
    <h2>Bibliothek</h2>
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Jahr</th>
          <th>Autor(en)</th>
        </tr>
      </thead>
      <xsl:for-each select="book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="year"/></td>
        <td>
          <xsl:value-of select="key('authors', author-ref)/first-name"/>
          <xsl:text> </xsl:text>
          <xsl:value-of select="key('authors', author-ref)/last-name"/>
        </td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>