2017-07-04 61 views
0

我想獲取由XML文件中的書籍元素引用的author元素的名稱,但我還沒有弄清楚如何訪問它。XSL:從XML中引用元素獲取數據(ref,id)

下面是我的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> 

這裏是如何看起來卻T.Pratchett而不是像我想有特里·普拉切特在表格單元格例。

Book Table

,如果有人知道如何解決這個問題,我將非常感激。 謝謝。

回答

0

您可以使用密鑰通過id屬性查找author元素。

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

非常感謝!這就是我一直在尋找的! –