The following stylesheet will return the requested result when applied to your example.
However, as I said in a comment to your question, there are many possible scenarios that your question does not cover. Specifically, what should happen to other children of A
, that are neither B
nor text nodes.
Note also that if A
is the root element (as in your example), the result be will be an ill-formed XML document.
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:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="A[B]">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="A[B]/text()">
<A>
<xsl:value-of select="."/>
</A>
</xsl:template>
</xsl:stylesheet>
Test input:
<root>
<A>Something <B>something else</B> more</A>
<A>Something <B>something else</B> <C>altogether</C> more</A>
<A>Something more</A>
<A>Something <C>altogether</C> more</A>
</root>
Result
<?xml version="1.0" encoding="UTF-8"?>
<root>
<A>Something </A>
<B>something else</B>
<A> more</A>
<A>Something </A>
<B>something else</B>
<C>altogether</C>
<A> more</A>
<A>Something more</A>
<A>Something <C>altogether</C> more</A>
</root>
Edit
If I understand better your requirement (which is not at all certain), you want to do something like:
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:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="A[B]">
<xsl:apply-templates select="B"/>
</xsl:template>
<xsl:template match="A/B">
<xsl:variable name="i" select="position()" />
<xsl:if test="$i=1">
<xsl:variable name="first-group" select="preceding-sibling::node()"/>
<xsl:if test="$first-group">
<A>
<xsl:copy-of select="$first-group"/>
</A>
</xsl:if>
</xsl:if>
<xsl:copy-of select="."/>
<xsl:variable name="this-group" select="following-sibling::node()[not(self::B) and count(preceding-sibling::B)=$i]"/>
<xsl:if test="$this-group">
<A>
<xsl:copy-of select="$this-group"/>
</A>
</xsl:if>
</xsl:template>
</xsl:stylesheet>