Strip whitespace and newlines from XML in Java

2019-01-08 00:44发布

Using Java, I would like to take a document in the following format:

<tag1>
 <tag2>
    <![CDATA[  Some data ]]>
 </tag2>
</tag1>

and convert it to:

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

4条回答
叛逆
2楼-- · 2019-01-08 01:09

As documented in an answer to another question, the relevant function would be DocumentBuilderFactory.setIgnoringElementContentWhitespace(), but - as pointed out here already - that function requires the use of a validating parser, which requires an XML schema, or some such.

Therefore, your best bet is to iterate through the Document you get from the parser, and remove all nodes of type TEXT_NODE (or those TEXT_NODEs which contain only whitespace).

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-08 01:12

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);
    }
}
查看更多
Viruses.
4楼-- · 2019-01-08 01:21

Try this code. read and write methods in FileStream ignore whitespace and indents.

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());  
}
查看更多
Luminary・发光体
5楼-- · 2019-01-08 01:23

recursively traverse the document. remove any text nodes with blank content. trim any text nodes with non-blank content.

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);
    }
}
查看更多
登录 后发表回答