1

我需要读取一个 XML 文件(如果存在 - 如果不存在,那么我将创建该文件),修改一些标签并将 xml 写回。我正在这样做

    InputStream in = new FileInputStream(userFile);
    SAXReader reader = new SAXReader();
    Document document = reader.read(in);

    Element root = document.getRootElement();
    ...

并写回

    FileUtils.writeByteArrayToFile(userFile, getFormatedXML(document).getBytes());

    ...

    private String getFormatedXML(Document doc) {
    try {
        String encoding = doc.getXMLEncoding();

        if (encoding == null)
            encoding = "UTF-8";

        Writer osw = new StringWriter();
        OutputFormat opf = new OutputFormat("  ", true, encoding);
        XMLWriter writer = new XMLWriter(osw, opf);
        writer.write(doc);
        writer.close();
        return osw.toString();
    } catch (IOException e) {
    }
    return "ERROR";
}

问题是,每次回写后,都会创建一个额外的换行符。如果我将 outputFormat 的参数从 true 切换为 false,则根本不会写入换行符。

有没有简单的方法来解决这个问题?

非常感谢豪克

4

1 回答 1

1

在 Java 中编写格式化 XML 的最佳方法是使用javax.xml.transform包,如下所示:

 TransformerFactory transfac = TransformerFactory.newInstance();
 transfac.setAttribute("indent-number", 2);
 Transformer trans = transfac.newTransformer();
 trans.setOutputProperty(OutputKeys.INDENT, "yes");
 trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
 trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
 Result result = new StreamResult(System.out);
 trans.transform(new DomSource(document), result);

而不是System.out,使用 aFileOutputStream作为您的目标文件。

顺便说一句,您提供的代码中有许多陷阱:

FileUtils.writeByteArrayToFile(userFile, getFormatedXML(document).getBytes());

这对于不同的编码是不安全的,因为您使用了使用默认平台编码的 String#getBytes(),并且很容易导致 XML 文档的编码标题不正确。

XMLWriter是一个 com.sun 实现特定的类,不能跨 JDK 移植。(这对您来说不太可能成为问题)

于 2012-03-20T10:34:49.487 回答