使用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());
解决方法:
工作解决方案遵循@Luiggi Mendoza的问题评论中的说明.
public static String trim(String input) {
BufferedReader reader = new BufferedReader(new StringReader(input));
StringBuffer result = new StringBuffer();
try {
String line;
while ( (line = reader.readLine() ) != null)
result.append(line.trim());
return result.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}