gpt4 book ai didi

java - 如何使用 JDOM 将独立的 ="no"添加到文件?

转载 作者:行者123 更新时间:2023-11-30 08:12:53 27 4
gpt4 key购买 nike

我找到了here如何将 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());
}

};

最佳答案

你的代码撒谎了;-)

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

关于java - 如何使用 JDOM 将独立的 ="no"添加到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com