在Java中从XML中删除空格和换行符

使用Java,我想采用以下格式的文档:

     

并将其转换为:

  

我尝试了以下内容,但它没有给我我期望的结果:

 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); } } 

递归遍历文档。 删除任何包含空白内容的文本节点。 修剪具有非空白内容的任何文本节点。

 public static void trimWhitespace(Node node) { NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); if(child.getNodeType() == Node.TEXT_NODE) { child.setTextContent(child.getTextContent().trim()); } trimWhitespace(child); } } 

正如在另一个问题的答案中所记录的那样,相关的函数将是DocumentBuilderFactory.setIgnoringElementContentWhitespace() ,但是 – 正如这里已经指出的那样 – 该函数需要使用validation解析器,这需要XML模式或其他类型。

因此,最好的办法是遍历从解析器获取的Document,并删除TEXT_NODE类型的所有节点(或仅包含空格的TEXT_NODE)。

试试这个代码。 FileStream中的write方法忽略空格和缩进。

 try { File f1 = new File("source.xml"); File f2 = new File("destination.xml"); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); } catch(IOException e7){ System.out.println(e7.getMessage()); }