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