Paladini
Paladini

Reputation: 4572

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. 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.

The file called "config.xml" is created with FileWriter, but without any line inside it.

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?

Upvotes: 0

Views: 597

Answers (1)

Ben
Ben

Reputation: 1927

You'll need to call write.flush() for the buffered content of the writer to be written to the file. This is due to usage of the PrintWriter(Writer x) constructor, which does not auto flush content by default. See the JavaDoc for more info.

Upvotes: 1

Related Questions