Search code examples
javaxmleclipsejdomjdom-2

create xml from java using Jdom


I'm using this code to create the generatedXml.xml file

Element FICHADAS = new Element("FICHADAS");
Document doc = new Document(FICHADAS);
doc.setRootElement(FICHADAS);
Element fichada = new Element("fichada");
fichada.addContent(new lement("N_Terminal").setText("XX"));
fichada.addContent(new Element("Tarjeta").setText("XX"));
fichada.addContent(new Element("Fecha").setText("XX"));
fichada.addContent(new Element("Hora").setText("XX"));
fichada.addContent(new Element("Causa").setText("XX"));
doc.getRootElement().addContent(fichada);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("generatedXml.xml"));

But I get an error in the last line (I'm using eclipse):

Multiple markers at this line - Unhandled exception type IOException - Unhandled exception type IOException


Solution

  • Your method should be throw the IOException or you have to use a try-catch-block arround your code.

    public void myMethod() throws IOException {
     ...
    }
    

    or

    try{
    Element FICHADAS = new Element("FICHADAS");
    Document doc = new Document(FICHADAS);
    doc.setRootElement(FICHADAS);
    Element fichada = new Element("fichada");
    fichada.addContent(new lement("N_Terminal").setText("XX"));
    fichada.addContent(new Element("Tarjeta").setText("XX"));
    fichada.addContent(new Element("Fecha").setText("XX"));
    fichada.addContent(new Element("Hora").setText("XX"));
    fichada.addContent(new Element("Causa").setText("XX"));
    doc.getRootElement().addContent(fichada);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, new FileWriter("generatedXml.xml"));
    } catch(IOException){
      // handle the exception.
    
    }