Concatenate values of elements to a variable with the usage of a template?

倖福魔咒の 提交于 2019-12-13 07:37:56

问题


The following data need to be concatenated. But the XML document which I received can have "zero to n" b elements. In other words if there are no b elements the xslt should still work correctly example:

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

Expected result

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

I was trying the following construction but I couldn't made it work.

<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-->

I hope some body can give me a hint? Regards Dirk


回答1:


You cannot use //b* to select all elements starting with b, since XPath is always doing an exact matching without wildcards (perhaps except for namespaces). So you need to use //*[starts-with(name(), "b")] to select the b elements

Then you can do the concatenation is in XPath alone with the string-join function:

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



回答2:


As simple as this (complete transformation):

<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>

When this transformation is applied on the provided (corrected for well-formedness) XML document:

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

the wanted, correct result is produced:

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


来源:https://stackoverflow.com/questions/14327033/concatenate-values-of-elements-to-a-variable-with-the-usage-of-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!