2

I intend to use XSLT to clean some unwanted symbols from the following data:

<Cart>
    <Row>
        <Ld>Restaurant/Cafe Bar &amp; Stores J-K,3</Ld>
        <Ln>Restaurant/Cafe Bar &amp; Stores J-K</Ln>
    </Row>
</Cart>

How can the following symbols be deleted

&amp;
/

the resulting data would be

<Cart>
    <Row>
        <Ld>Restaurant,Cafe Bar, Stores J-K,3</Ld>
        <Ln>Restaurant, Cafe Bar, Stores J-K</Ln>
    </Row>
</Cart>
Abiodun
  • 959
  • 6
  • 17
  • 38
  • 1
    lee, It seems to me that by "clean" you don't exactly mean "delete". For example, do you want the result to contain "RestaurantCafe", or "Restaurant Cafe" or "Restaurant-Cafe", or ... ? Except for the first case, in all remaining cases you actually need to *replace*. Please, to avoid this confusion, edit the question and provide the exact wanted result (it is a good rule to know that if you haven't provided the exact wanted result in *any* question, then the question isn't well-defined). – Dimitre Novatchev Sep 02 '12 at 21:41

2 Answers2

3

You can use the translate() function:

Applied to an identity transform to replace those characters with a ,:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:template match="@*| node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="translate(., '&amp;/', ',,')"/>
    </xsl:template>
</xsl:stylesheet>

With XSLT/XPath 2.0 you can use the replace() function, which provides a more robust capability for find/replace operations and normalization of leading/trailing whitespace, etc.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:template match="@*| node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="replace(., '\s?(&amp;|/)\s?', ', ')"/>
    </xsl:template>
</xsl:stylesheet>
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • @ Mads Hansen, can it be replaced with a space or a comma? because the values close up, especially the ones with '/' – Abiodun Sep 02 '12 at 20:26
  • That's pretty easy, just replace the `''` with `'  '` (two spaces) in that translate call, replacing them with spaces rather than nothing. – Flynn1179 Sep 02 '12 at 21:52
  • 1
    Another XSLT 1.0 solution would be a recursive template where you could provide the string that you want to find and what to replace it with. It would make it easier to replace ` & ` with `, `. http://stackoverflow.com/a/7523245/14419 – Mads Hansen Sep 03 '12 at 01:36
0

You can use the replace function.

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93