Java 如何使用“创建和编写XML”;文件「;(XOM)内容
我正在尝试使用“XOM”创建一个XML文件,这是一个Java库。我用XOMAPI创建了XML的结构,但是现在我需要创建一个具有这种结构的文件来持久化这些数据 名为“config.xml”的文件是用FileWriter创建的,但里面没有任何行 这是我的代码:Java 如何使用“创建和编写XML”;文件「;(XOM)内容,java,xml,serialization,Java,Xml,Serialization,我正在尝试使用“XOM”创建一个XML文件,这是一个Java库。我用XOMAPI创建了XML的结构,但是现在我需要创建一个具有这种结构的文件来持久化这些数据 名为“config.xml”的文件是用FileWriter创建的,但里面没有任何行 这是我的代码: // Creating the main element Element projetoMusica = new Element("projetoMusica"); // Creating the childs of
// Creating the main element
Element projetoMusica = new Element("projetoMusica");
// Creating the childs of "projetoMusica".
Element notas = new Element("notas");
Element acordes = new Element("acordes");
Element campos = new Element("campos");
Element acordeNota = new Element("acordeNota");
Element campoNota = new Element("campoNota");
Element campoAcorde = new Element("campoAcorde");
// Associating the structure
projetoMusica.appendChild("\n");
projetoMusica.appendChild(notas);
projetoMusica.appendChild("\n");
projetoMusica.appendChild(acordes);
projetoMusica.appendChild("\n");
projetoMusica.appendChild(campos);
projetoMusica.appendChild("\n");
projetoMusica.appendChild(acordeNota);
projetoMusica.appendChild("\n");
projetoMusica.appendChild(campoNota);
projetoMusica.appendChild("\n");
projetoMusica.appendChild(campoAcorde);
// Creating a Document object (from "XOM" API).
Document doc = new Document(projetoMusica);
try {
FileWriter xmlFILE = new FileWriter("C:\\config.xml");
PrintWriter write = new PrintWriter(xmlFILE);
write.print(doc.toXML());
} catch (IOException ex) {
Logger.getLogger(Administracao.class.getName()).log(Level.SEVERE, null, ex);
}
如何才能正确写入此.xml文件?您需要调用
write.flush()。这是由于使用了PrintWriter(Writer x)
构造函数,默认情况下该构造函数不会自动刷新内容。有关详细信息,请参阅。谢谢!!最后我还需要使用write.close(),不是吗?是的,理想情况下,完成后调用close()。