With XSLT 1.0, the regex methods of XSLT 2.0 are generally unavailable. Is there any non-regex way of replacing multiple fields in a node in a source xml document, for example to convert:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc [[field1]] def [[field2]] ghi</source>
</file>
</xliff>
to:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc F def F ghi</source>
</file>
</xliff>
EDIT 1
I just realized Dimitre's version uses recursion and is quite similar; so my opening sentence seems silly now.
Here's a version that uses recursion:
match="source/text()"
matches all the text in 'source' node as one string and passes it to the named pattern 'replace'. 'replace' looks for occurrences of the beginning and ending delimiters ('[[' and ']]'), and if found splits the text at (and thus ignoring) the delimiters, inserts the replacement string, and passes all that to itself to repeat the process.I say "split", but given the lack of a real
split()
in XPath 1.0, we can get by teaming upsubstring-before()
andsubstring-after()
.Given the text in the source,
'abc [[field1]] def [[field2]] ghi'
, the recursion goes like this, showing how it's split, replaced, and passed:'abc ' + 'F' + def [[field2]] ghi'
, passed again into 'replacement''abc F def ' + 'F' + ' ghi'
, passed again into 'replacement''abc F def F ghi'
is passed back up tomatch="source/text()"
Here's how it looks with
xsltproc
:I hope this helps.
I. XSLT 1.0 Solution:
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
II. XSLT 2.0 Solution (just for comparison):
You can use Java inside XSL, example for replaceAll:
pattern is a regexp. For further info see: String javadoc
EXSLT has some good functions for you. If you need to replace simple strings, try str:replace. An XSLT 1.0 template implementation is given.