I have this sample document:
<root>
<span class="a">te</span><span class="a">st</span> <span class="a">tag</span>
some other text
<span class="b">keep</span>
</root>
I would like to have something like this:
<root>
<span class="a">test tag</span>
some other text
<span class="b">keep</span>
</root>
Or at least this:
<root>
<span class="a">test</span> <span class="a">tag</span>
some other text
<span class="b">keep</span>
</root>
There will be variable count of class="a"
spans. Is it possible in XSLT?
EDIT
tried to solve:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*/span[@class = 'a']"/>
<xsl:template match="*/span[@class = 'a'][1]">
<span class="a">
<xsl:for-each select="../span[@class = 'a'] | ../text()[. = ' ']">
<xsl:choose>
<xsl:when test=". = ' '">
<xsl:copy/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="./text()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</span>
</xsl:template>
</xsl:stylesheet>
but when I have this input?
<root>
<span class="a">te</span><span class="a">st</span> <span class="a">tag</span>
some other text
<span class="b">keep</span>
<span class="a">te</span><span class="a">st</span> <span class="a">tag</span>
</root>
How to solve this?
The second variant can be achieved using:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="grp"
match="span[@class='a'][preceding-sibling::node()[1][self::span[@class='a']]]"
use="generate-id(preceding-sibling::span[@class='a'][not(preceding-sibling::node()[1][self::span[@class='a']])][1])" />
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="span[@class='a'][not(preceding-sibling::node()[1][self::span[@class='a']])]" priority="1">
<span class="a">
<xsl:for-each select=". | key('grp', generate-id())" >
<xsl:value-of select="."/>
</xsl:for-each>
</span>
</xsl:template>
<xsl:template match="span[@class='a']"/>
</xsl:stylesheet>
With some more work, you could include the interspersing white-space only text nodes in the group. Alternatively, look at a technique known as "sibling recursion".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.