Search code examples
regexcoldfusion

How do I remove all excess whitespace from an XML string using ColdFusion?


I receive an XML string from a client in a format like the following...

<root>
   <result success="1"/>
   <userID>12345</userID>
   <classID>56543</classID>
</root>

I need to compress this string down to the following...

<root><result success="1"/><userID>12345</userID><classID>56543</classID></root>

So, all of the whitespace is removed, except inside of the tag (so the space still exists between "result" and "success").

I have used replace statements to remove line breaks, carriage returns, etc, but I can't remove spaces while ignoring the spaces inside tags. Is there a way to use a regular expression or some other method to accomplish this?


Solution

  • The below regx would match the spaces which are not within the tags,

    [\s]+(?![^><]*>)
    

    OR

    [\s]+(?![^><]*(?:>|<\/))
    

    Just replace the matched spaces with an empty string.

    DEMO

    Edit Starts Here

    From the comments - in the context of ColdFusion it works like this...

    strClean = REReplace(strOriginal,"[\s]+(?![^><]*(?:>|<\/))","","All");