当前位置: 代码迷 >> J2EE >> 求java正则表达式去掉xml中多余的空格,该怎么解决
  详细解决方案

求java正则表达式去掉xml中多余的空格,该怎么解决

热度:10   发布时间:2016-04-22 01:53:21.0
求java正则表达式去掉xml中多余的空格
兄弟有一个xml文本,样例如下:
<cc>
  <c code="3">100</c>
  <c code="5">100</c>
</cc>

这个文本如果去掉换行符,则是
<cc> <c code="3">100</c> <c code="5">100</c></cc>

我想用正则表达式去掉<cc> <c code="3">和</c> <c code="5">之间的空格,但是不知道怎么写,求教大家了。

------解决方案--------------------
String a="E:/A S3/pengqi/Shoping/src/ckstudio/db/"; 

a.replaceAll("/","\\");

不知道合不合适你的要求
------解决方案--------------------
Java code
public class Replacement {    public static void main(String[] args) {        String str =            "<cc>\r\n" +            "  <c code=\"3\">100</c>\r\n" +            "  <c code=\"5\">100</c>\n" +            "</cc>";                System.out.println(str);        System.out.println();                str = str.replaceAll("(?<=>)\\s+(?=<)", "");        System.out.println(str);    }}
------解决方案--------------------
为了不把标签中元素中纯空格替换掉的话(像下面 /cc/c[@code='5'] 中的空格),可以改成这样:

Java code
public class Replacement {    public static void main(String[] args) {        String str =            "<cc>\r\n" +            "  <c \n" +            "  \r\n\t" +            "\r\n" +            "\t  code=\"3\">   \n" +            "   100\t   \r\n" +            " \n" +            "  </c>\r\n" +            "  <c code=\"5\"> </c>\t\n" +            "\n  \t\n\t" +            "</cc>";                System.out.println(str);        System.out.println();                str = str.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", "");        System.out.println(str);    }}