2013-01-14 18 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,请尝试编辑的代码。 –