繁体   English   中英

如何使用JDOM在文件中添加standalone =“ no”?

[英]How do I add standalone=“no” TO A FILE using JDOM?

我在这里找到如何将XML文档的打印输出覆盖到Eclipse控制台中,使其包含standalone =“ no”的方法 ,但是如何将standalone =“ no”写入文件? 我尝试将同一文档写入文件,但仍无法打印出独立=“ 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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM