2013-03-19 122 views
5

我現在正在學習XSL並對交叉引用有疑問。 我的目標XML文件的結構是這樣的:XSL交叉引用

<XML> 
    <Model> 
     <packedElement typ="class" id="1"/> 
     <packedElement typ="class" id="2"/> 
     <packedElement typ="class" id="3"/> 
    </Model> 
    <Elements> 
     <Element idref="1"> 
      <Attributes comment="comment 1."/> 
     </Element> 
     <Element idref="2"> 
      <Attributes comment="comment 2."/> 
     </Element> 
     <Element idref="3"> 
      <Attributes comment="comment 3."/> 
     </Element> 
    </Elements> 
</XML> 

我想連接ID = IDREF。我的目標是列出所有packedElements並打印他們的評論。 你們能幫我嗎?

我試圖用key-funktion來解決它,但我並不是非常成功。

編輯:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"> 
<xsl:output method="xml" encoding="UTF-8"/> 

<xsl:key name="CommentK" match="Element" use="@idref"/> 


<xsl:template match="XML"> 
<XML> 
<xsl:apply-templates/> 
</XML> 
</xsl:template> 

<xsl:template name="Start" match="packedElement"> 
<xsl:variable name="TEST" select="@id"/> 
<xsl:variable name="Comment"> 
<xsl:call-template name="FindComment"> 
<xsl:with-param name="test2" select="@id"/> 
</xsl:call-template> 
</xsl:variable> 
<content comment="{$Comment}" id ="{@id}" test="{$TEST}"></content> 
</xsl:template> 

<xsl:template name="FindComment"> 
<xsl:param name="test2"/> 

<xsl:for-each select="key('CommentK', '$test2')"> 

<xsl:value-of select="Attributes/@comment"/> 

</xsl:for-each> 

</xsl:template> 

</xsl:stylesheet> 

XSLT版本爲2.0。 (順便說一句有人可以告訴我.XSLT和的.xsl之間的區別?)

+0

XSLT 1.0或2.0? – 2013-03-19 14:27:33

+0

你的嘗試是什麼樣的?你想讓結果看起來像什麼? – JLRishe 2013-03-19 14:33:22

+0

我認爲你的嘗試幾乎可以工作,除了你使用''test2''這是_string value_「$ test2」。它應該只是'key('CommentK',$ test2)'。我認爲'FindComment'和'for-each'雖然是過度的。 Martin Honnen的回答很好。 – JLRishe 2013-03-19 15:05:49

回答

6

嘗試

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

<xsl:output indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:key name="el-by-idref" match="Elements/Element" use="@idref"/> 

<xsl:template match="XML"> 
    <xsl:copy> 
    <xsl:apply-templates select="Model/packedElement"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="Model/packedElement"> 
    <content comment="{key('el-by-idref', @id)/Attributes/@comment}" id="{@id}" test="{@id}"/> 
</xsl:template> 



</xsl:stylesheet> 

這樣,你得到

<XML> 
    <content comment="comment 1." id="1" test="1"/> 
    <content comment="comment 2." id="2" test="2"/> 
    <content comment="comment 3." id="3" test="3"/> 
</XML> 
+0

哇..非常快速的幫助感謝!那就是我所尋找的。這是一個非常簡單的目標文件,現在我嘗試編寫big-xml的代碼。謝謝! – gs3rr4 2013-03-19 15:02:15