2010-03-19 40 views
1

爲XSLT中的「for-each」表達式創建值我需要瀏覽此xml樹。如何藉助參數

<publication> 
    <corporate> 
     <contentItem> 
      <metadata>meta</metadata> 
      <content>html</content> 
     </contentItem> 
     <contentItem > 
      <metadata>meta1</metadata> 
      <content>html1</content> 
     </contentItem> 
    </corporate> 
    <eurasia-and-africa> 
     ... 
    </eurasia-and-africa> 
    <europe> 
     ... 
    </europe> 
</publication> 

,並將其轉換這個樣式表的HTML

<ul> 
    <xsl:variable name="itemsNode" select="concat('publicationManifest/',$group,'/contentItem')"></xsl:variable> 
    <xsl:for-each select="$itemsNode"> 
     <li> 
     <xsl:value-of select="content"/> 
     </li> 
    </xsl:for-each> 
</ul> 

$組是例如「企業」組的名稱的參數。我在編譯這個樣式表時遇到錯誤。 SystemID:D:\ 1 \ contentsTransform.xslt

Engine name: Saxon6.5.5 
Severity: error 
Description: The value is not a node-set 
Start location: 18:0 

發生了什麼事?

+0

對於該問題+1。在我的回答中找到你的解決方案。 – 2010-03-19 16:33:14

+0

我很高興「它有效」。如果是這樣,你可以接受答案:) – 2010-03-19 20:06:27

回答

2

在XSLT這可以通過以下方式可以容易地實現:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:param name="pGroup" select="'corporate'"/> 

<xsl:template match="/"> 
    <ol> 
     <xsl:for-each select="/*/*[name()=$pGroup]/contentItem"> 
     <li> 
      <xsl:value-of select="content"/> 
     </li> 
     </xsl:for-each> 
    </ol> 
</xsl:template> 
</xsl:stylesheet> 

當這個變換所提供的XML文檔應用,有用結果產生

<ol> 
    <li>html</li> 
    <li>html1</li> 
</ol> 

做筆記使用the XPath name() function

+0

非常感謝。工作正常。 – Artic 2010-03-19 17:11:47

2

您無法構建和評估動態XPath表達式。而99.9%的時間,你不需要。推論:如果你覺得需要動態評估XPath,你很可能做錯了事情。

聲明你$pGroup參數:

<xsl:param name="pGroup" select="''" /> 

...做一個模板,爲您的文檔元素(<publication>):

<xsl:template match="publication"> 
    <body> 
    <!-- select only elements with the right name here --> 
    <xsl:apply-templates select="*[name() = $pGroup]" /> 
    </body> 
</xsl:template> 

...和一個任意元素包含<contentItem>元素:

<xsl:template match="*[contentItem]"> 
    <ul> 
    <xsl:apply-templates select="contentItem" /> 
    </ul> 
</xsl:template> 

...,一個用於<contentItem>元素本身:

<xsl:template match="contentItem"> 
    <li> 
    <xsl:value-of select="content" /> 
    </ul> 
</xsl:template> 

完成。

+0

我只需要顯示一個節點的內容 - 例如,並需要通過參數來管理它。 – Artic 2010-03-19 17:03:26

+0

@Artic:查看已更改的答案。 – Tomalak 2010-03-19 17:17:09