xsl-list
[Top] [All Lists]

Re: [xsl] Usage of XSLT in the field of text replacement.

2008-10-09 01:14:15
Here is a 2.0 solution for this (let's say this file is test.xsl),

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
                       version="2.0">

  <xsl:output method="xml" indent="yes" />

  <xsl:variable name="replacement-data"
select="tokenize(unparsed-text('temp.ini','UTF-8'),'\s+')" />
  <xsl:variable name="regex-pattern" select="string-join(for $x in
$replacement-data return (if
(starts-with(substring-before($x,'|'),'[') and
ends-with(substring-before($x,'|'),']')) then
concat('\',substring(substring-before($x,'|'),0,string-length(substring-before($x,'|'))),'\]')
else substring-before($x,'|')),'|')" />

  <xsl:template match="doc">
    <d>
      <xsl:apply-templates select="para" />
    </d>
  </xsl:template>

  <xsl:template match="para">
    <p>
      <xsl:analyze-string select="."
                          regex="{$regex-pattern}">
        <xsl:matching-substring>
          <xsl:variable name="x" select="." />
          <xsl:value-of
select="substring-after($replacement-data[substring-before(., '|') =
$x], '|')" />
        </xsl:matching-substring>
        <xsl:non-matching-substring>
          <xsl:value-of select="." />
        </xsl:non-matching-substring>
      </xsl:analyze-string>
    </p>
  </xsl:template>

</xsl:stylesheet>

The other files are,

input.xml

<doc>
  <para>line no. 1</para>
  <para>line no. 2</para>
  <para>para number. 50</para>
  <para>example of [text] replacement</para>
</doc>

temp.ini

1|ONE
2|TWO
3|THREE
50|FOUR
[text]|[TEXT]

When the transformation is run as following:

java net.sf.saxon.Transform input.xml test.xsl

The output produced is,

<?xml version="1.0" encoding="UTF-8"?>
<d>
   <p>line no. ONE</p>
   <p>line no. TWO</p>
   <p>para number. FOUR</p>
   <p>example of [TEXT] replacement</p>
</d>

Hope this helps ...

On Wed, Oct 8, 2008 at 4:09 PM, J. S. Rawat <jrawat(_at_)aptaracorp(_dot_)com> 
wrote:
Hi
Can xslt2.0 play a role in the field of text replacement. I want to
transform an xml to another xml and want to replace some text as well. For
that purpose I want to restore "find and replace" text in a separate file
with pipe separated delimeter.

Input
<doc>
<para>line no. 1</para>
<para>line no. 2</para>
<para>para number. 50</para>
<para>example of [text] replacement</para>
</doc>

OUTPUT
<d>
<p>line no. ONE</p>
<p>line no. TWO</p>
<p>para number. FIFTY</p>
<para>example of [TEXT] replacement</para>
</d>

temp.ini
1|ONE
2|TWO
3|THREE
[text]|[TEXT]



-- 
Regards,
Mukul Gandhi

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>