如何使用xstream删除xml中的空格和回车符

时间:2012-07-30 18:40:44

标签: xstream

我正在尝试线性化(删除空格和回车)以压缩XML。

输入

<?xml version="1.0" encoding="UTF-8"?> 
<books> 
    <book> 
       <title>Basic XML</title> 
       <price>100</price> 
       <qty>5</qty> 
    </book> 
    <book> 
        <title>Basic Java</title> 
        <price>200</price> 
        <qty>15</qty> 
    </book> 
</books>

输出如下。

77u / PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4gDQo8Ym9va3M + IA0KICAg PGJvb2s + IA0KICAgICAgIDx0aXRsZT5CYXNpYyBYTUw8L3RpdGxlPiANCiAgICAgICA8cHJpY2U + MTAwPC9wcmljZT4gDQogICAgICAgPHF0eT41PC9xdHk + IA0KICAgPC9ib29rPiANCiAgIDxib29r PiANCiAgICAgPHRpdGxlPkJhc2ljIEphdmE8L3RpdGxlPiANCiAgICAgPHByaWNlPjIwMDwvcHJp Y2U + IA0KICAgICA8cXR5PjE1PC9xdHk + IA0KICAgPC9ib29rPiANCjwvYm9va3M +

要转换的代码如下。

public class XMLCompactTest {

public void testCompact() throws SAXException, IOException,
        ParserConfigurationException {

    final InputStream is =
            XMLCompactTest.class.getResourceAsStream("/example.xml");

    final byte[] bytes = IOUtils.toByteArray(is);
    final byte[] compactedBytes = compactXml(bytes);

    final String after = new String(compactedBytes);

    System.out.println(after);
}

 public static byte[] compactXml(final byte[] value)
        throws SAXException, IOException, ParserConfigurationException {

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final XStream xs = new XStream();
    xs.autodetectAnnotations(true);
    xs.setMode(XStream.ID_REFERENCES);
    //xs.marshal(value, new CompactWriter(new OutputStreamWriter(bout, "UTF-8")));
    xs.marshal(value, new CompactWriter(new OutputStreamWriter(bout)));

    return bout.toByteArray();
}

}

非常感谢任何帮助,我已经提到了其他处理压缩xml的答案,它们似乎对我不起作用。我正在使用xstream 1.4.3。

我期待一行压缩和解码xml。

亲切的问候。

1 个答案:

答案 0 :(得分:0)

你在这里做的是编组一个字节数组。这当然会带来一些奇特的结果。

我只需手动编写compactXml()方法。

public static String compactXml(final byte[] value) {
   String in = new String(value, "UTF-8");
   StringBuffer sb = new StringBuffer();
   for(int i=0;i<in.length();i++) {
      char c = in.charAt(i);
      if(c != '\n' || c != ' ') {
         sb.append(c);
      }
   }
return sb.toString();
}