2013-01-14 21 views
0

以下數據需要連接。但是我收到的XML文檔可以有「零到n」b元素。換句話說,如果有否b元素的XSLT應該仍然工作正常例如:使用模板將元素的值連接到變量?

<a> 
    <b1>Some</b2> 
    <b2>data</b2> 
    <b3>what</b3> 
    <b4>need</b4> 
    <b5>to</b5> 
    <b6>be</b6> 
    <b7>concatenated</b7> 
</a> 

預期結果

<a> 
    <b1>Some data what need to be concatenated</b1> 
</a> 

我嘗試下面的結構,但我不能使它工作。

<xsl:variable name="details" select="//b*"/> 
<xsl:for-each select="$details"> 
    <!-- how can I concatenate the values of the b's to a variable????--> 
</xsl:for-each> 
<!-- Process the variable for further needs--> 

我希望有些身體可以給我一個提示嗎? 關注Dirk

+0

的示例數據沒有出來throught。 一些 數據 什麼 需要 再次連接起來 Dirk

回答

2

您不能使用// b *來選擇所有以b開頭的元素,因爲XPath始終在沒有通配符的情況下進行完全匹配(可能除名稱空間外)。所以你需要使用// * [starts-with(name(),「b」)]來選擇b元素

然後你可以在XPath中單獨使用字符串連接功能來連接:

string-join(//*[starts-with(name(), "b")]/text(), " ") 
1

因爲這(完全轉化)作爲簡單:

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

<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*[starts-with(name(), 'b')][1]"> 
    <xsl:element name="{name()}" namespace="{namespace-uri()}"> 
    <xsl:sequence select="../*[starts-with(name(), 'b')]/string()"/> 
    </xsl:element> 
</xsl:template> 
<xsl:template match="text()[true()]| *[starts-with(name(), 'b')][position() gt 1]"/> 
</xsl:stylesheet> 

當這個變換所提供的(校正爲良好性)的XML文檔應用:

<a> 
    <b1>Some</b1> 
    <b2>data</b2> 
    <b3>what</b3> 
    <b4>need</b4> 
    <b5>to</b5> 
    <b6>be</b6> 
    <b7>concatenated</b7> 
</a> 

的希望,正確的結果產生

<a> 
    <b1>Some data what need to be concatenated</b1> 
</a> 
+0

感謝學到了很多在過去的2天。是的,它工作。但我在運行時得到錯誤。錯誤]:/ a/text()[1]的模糊規則匹配。我如何解釋這些? – Dirk

+0

@Dirk,請嘗試編輯的代碼。 –