2017-07-04 63 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

非常感谢!这就是我一直在寻找的! –