Strip extra spaces in a XML stringTag(s): XML


This can be useful to reduce the size of a file or before writting a message to a queue or the network.
public class XMLStripSpaces {
  public static void main (String [] args) {
      String test1 = "<tag>test 1</tag>    <tag>test 2</tag> ";
      String out1 = test1.replaceAll(">\\s+<", "><");
      System.out.println(test1);
      System.out.println(out1);

      System.out.println("");

      String test2 = "<tag>test 3</tag> \n<tag>test 4</tag> ";
      String out2 = test2.replaceAll(">\\s+<", "><");
      System.out.println(test2);
      System.out.println(out2);

      /*
      output :

      <tag>test 1</tag>    <tag>test 2</tag>
      <tag>test 1</tag><tag>test 2</tag>

      <tag>test 3</tag>
      <tag>test 4</tag>
      <tag>test 3</tag><tag>test 4</tag>
      */
  }
}
One drawback is that the spaces inside tags are stripped too. The following example preserves those spaces inside a tag.
public class XMLStripSpaces {
   public static void main (String [] args) {
       String test1 = "<tag>test 1</tag>    <tag>test 2</tag> <tag> </tag>";
       String out1 = test1.replaceAll("(?!>\\s+</)(>\\s+<)", "><");
       System.out.println(test1);
       System.out.println(out1);


       /*
       output :
         <tag>test 1</tag>    <tag>test 2</tag> <tag> </tag>
         <tag>test 1</tag><tag>test 2</tag><tag> </tag>

       */
   }
 }

blog comments powered by Disqus