简体   繁体   English

如何使用“文档”(XOM)内容创建和编写XML

[英]How to create and write an XML with “Document” (XOM) content

I'm trying to create a XML file using "XOM", a library for Java. 我正在尝试使用Java库“ XOM”创建XML文件。 I created the structure of my XML with XOM API, but now I need to create a file with this structure, to persist this data. 我使用XOM API创建了XML的结构,但是现在我需要使用此结构创建一个文件,以持久存储此数据。

The file called "config.xml" is created with FileWriter, but without any line inside it. 名为“ config.xml”的文件是使用FileWriter创建的,但内部没有任何行。

Here's my code: 这是我的代码:

    // 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);
    }

What can I do to write properly inside this .xml file? 我该怎么做才能在此.xml文件中正确编写?

You'll need to call write.flush() for the buffered content of the writer to be written to the file. 您需要调用write.flush() ,以便将写入器的缓冲内容写入文件。 This is due to usage of the PrintWriter(Writer x) constructor, which does not auto flush content by default. 这是由于使用了PrintWriter(Writer x)构造函数,该构造函数默认情况下不会自动刷新内容。 See the JavaDoc for more info. 有关更多信息,请参见JavaDoc

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

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