在Java中从XML中删除空格和换行符 [英] Strip whitespace and newlines from XML in Java
本文介绍了在Java中从XML中删除空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java,我想采用以下格式的文档:
Using Java, I would like to take a document in the following format:
<tag1>
<tag2>
<![CDATA[ Some data ]]>
</tag2>
</tag1>
并将其转换为:
<tag1><tag2><![CDATA[ Some data ]]></tag2></tag1>
我尝试了以下内容,但它没有给我我期望的结果:
I tried the following, but it isn't giving me the result I am expecting:
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的问题评论中的说明门多萨。
Working solution following instructions in the question's comments by @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);
}
}
这篇关于在Java中从XML中删除空格和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文