在 Java 中从 XML 中去除空格和换行符
使用Java,我想采用以下格式的文档:
<tag1>
<tag2>
<![CDATA[ Some data ]]>
</tag2>
</tag1>
并将其转换为:
<tag1><tag2><![CDATA[ Some data ]]></tag2></tag1>
我尝试了以下方法,但它没有给我带来我所期望的结果:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new FileInputStream("/tmp/test.xml"));
Writer out = new StringWriter();
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "no");
tf.transform(new DOMSource(doc), new StreamResult(out));
System.out.println(out.toString());