1

我在这里找到了如何将 XML 文档的打印输出覆盖到我的 Eclipse 控制台,以便它包含Standalone = "no",但是我如何将Standalone = "no"写入文件?我尝试将相同的文档写入文件,但它仍然不会打印Standalone = "no"。换句话说,当我尝试写入文件时,被覆盖的方法不起作用。

在写入文件时我应该覆盖其他一些方法吗?这里有什么问题?

private static void writeXML() {

try {

Document doc = new Document();

Element theRoot = new Element("tvshows");
doc.setRootElement(theRoot);

Element show = new Element("show");
Element name = new Element("name");
name.setAttribute("show_id", "show_001");

name.addContent(new Text("Life on Mars"));

Element network = new Element("network");
network.setAttribute("country", "US");

network.addContent(new Text("ABC"));

show.addContent(name);
show.addContent(network);

theRoot.addContent(show);

//-----------------------------

Element show2 = new Element("show");
Element name2 = new Element("name");
name2.setAttribute("show_id", "show_002");

name2.addContent(new Text("Life on Mars"));

Element network2 = new Element("network");
network2.setAttribute("country", "UK");

network2.addContent(new Text("BBC"));

show2.addContent(name2);
show2.addContent(network2);

theRoot.addContent(show2);

XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat(), XMLOUTPUT);
//xmlOutput.output(doc, System.out);

xmlOutput.output(doc, new FileOutputStream(new File("./src/jdomMade.xml")));

System.out.println("The file has been written");

}
catch (Exception ex){
    ex.printStackTrace();
}


}

public static final XMLOutputProcessor XMLOUTPUT = new AbstractXMLOutputProcessor() {
@Override
protected void printDeclaration(final Writer out, final FormatStack fstack) throws IOException {
    write(out, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?> ");
    write(out, fstack.getLineSeparator());
}

};
4

1 回答 1

1

您的代码在于 ;-)

xmlOutput.output(doc, new FileOutputStream(new File("./src/jdomMade.xml")));

System.out.println("The file has been written");

println 表示文件已写入,但尚未写入。

只有在文件被刷新和关闭时才会写入文件。你不要那样做。

您应该在代码中添加 try-with-resources:

try (FileOutputStream fos = new FileOutputStream(new File("./src/jdomMade.xml"))) {
    xmlOutput.output(doc, fos);
}

System.out.println("The file has been written");
于 2015-05-08T04:37:25.797 回答