I have an element <mixed>
that contains mixed content. Is it possible to use XSLT (2.0) to wrap all “words” (delimited by the pattern \s+
, for example) inside <mixed>
in a <w>
tag, descending into inline elements when necessary? For example, given the following input:
<mixed>
One morning, when <a>Gregor Samsa</a>
woke from troubled dreams, he found
himself transformed in his bed into
a <b><c>horrible vermin</c></b>.
</mixed>
I want something like the following output:
<mixed>
<w>One</w> <w>morning,</w> <w>when</w> <a><w>Gregor</w> <w>Samsa</w></a>
<w>woke</w> <w>from</w> <w>troubled</w> <w>dreams,</w> <w>he</w> <w>found</w>
<w>himself</w> <w>transformed</w> <w>in</w> <w>his</w> <w>bed</w> <w>into</w>
<w>a</w> <b><c><w>horrible</w></c></b> <w><b><c>vermin</c></b>.</w>
</mixed>
Dimitre Novatchev provided a template in an answer to this related question that goes much of the way to solving this, but does not satisfy the following requirements:
Inline elements that terminate within a “word” should be split so that a single
<w>
element contains the whole “word.” Otherwise there would be invalid XML, such as:<w>a</w> <w><b><c>horrible</w> <w>vermin</c></b>.</w>
However, this template detaches the punctuation
.
aftervermin
and produces:<w>a</w> <b><c><w>horrible</w> <w>vermin</w></c></b> <w>.</(w>
(Edit: None of the current 3 answers satisfy this requirement.)
The split token must not be discarded. Consider the similar task of wrapping non-coefficient numbers in
<sub>
tags in the context of a chemical formula. For example,<reactants>2H2 + O2</reactants>
becomes<reactants>2H<sub>2</sub> + O<sub>2</sub></reactants>
. This is not possible using thetokenize
function because it simply discards the separator. Instead we will probably have to fall back onanalyze-string
.
If not XSLT, what is the best method to do this?