2

我正在尝试将(删除空格和回车)线性化为紧凑的 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+

要转换的代码如下。

公共类 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。

亲切的问候。

4

1 回答 1

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();
}
于 2012-08-06T12:44:22.397 回答