Nell’articolo precedente abbiamo visto nel dettaglio come leggere un file XML mentre in questo vedremo come scrivere su un file e un esempio sia di lettura che scrittura.
Scrivere un file XML
Per poter scrivere un file XML, il concetto non cambia rispetto alla lettura, e gli oggetti da utilizzare sono più o meno gli stessi. Occorre pertanto creare un oggetto Document e assegnargli un elemento radice in fase di costruzione:
Element rootElement = new Element("ROOT");
Document document = new Document(rootElement);
Possiamo quindi assegnare all’elemento radice, attributi e figli:
Element child1 = new Element("CHILD1");
rootElement.addContent(child1);
Element child2 = new Element("CHILD2");
child2.setText("a text");
child1.addContent(child2);
rootElement.setAttribute("attName", "attVal");
La struttura create nell’oggetto document sarà la seguente:
<ROOT attName="attVal">
<CHILD1>
<CHILD2>a text</CHILD2>
</CHILD1>
</ROOT>
Per far sì che la struttura venga scritta, abbiamo bisogno di introdurre una nuova classe: XMLOutputter. Come dice la parola stessa, questa classe si preoccupa di eseguire l’output della struttura XML creata:
XMLOutputter outputter = new XMLOutputter();
outputter.output(document, new FileOutputStream("foo.xml"));
Il metodo output prende in argomento l’oggetto Document e un oggetto OutputStream su cui scrivere il document. Da notare che se il file passato allo stream non esiste, esso viene creato.
Qui di seguito trovate due listati di programmi: il primo scriverà una lista delle cose da fare su un file XML. Il secondo leggerà il file creato e ne stamperà a schermo un resoconto.
Programma 1: Il writer
import org.jdom.*;
import org.jdom.output.*;
import java.io.*;
public class JDOMWriter {
public static void main(String[] args) {
try {
//Elemento radice
Element root = new Element("TODO_LIST");
//Documento
Document document = new Document(root);
//Creazione di tre elementi figli denominato ITEM
//a ciascuno dei quali vengono settati tre attributi
//e viene aggiunto un elemento figlio contenente
//la descrizione della cosa da fare
Element item1 = new Element("ITEM");
item1.setAttribute("importanza", "3");
item1.setAttribute("perc_completamento", "75");
item1.setAttribute("completata", "no");
Element descr1 = new Element("DESCR");
descr1.setText("Fare la spesa");
item1.addContent(descr1);
root.addContent(item1);
Element item2 = new Element("ITEM");
item2.setAttribute("importanza", "7");
item2.setAttribute("perc_completamento", "100");
item2.setAttribute("completata", "si");
Element descr2 = new Element("DESCR");
descr2.setText("Stendere i panni");
item2.addContent(descr2);
root.addContent(item2);
Element item3 = new Element("ITEM");
item3.setAttribute("importanza", "4");
item3.setAttribute("perc_completamento", "0");
item3.setAttribute("completata", "no");
Element descr3 = new Element("DESCR");
descr3.setText("Cucinare");
item3.addContent(descr3);
root.addContent(item3);
//Creazione dell'oggetto XMLOutputter
XMLOutputter outputter = new XMLOutputter();
//Imposto il formato dell'outputter come "bel formato"
outputter.setFormat(Format.getPrettyFormat());
//Produco l'output sul file xml.foo
outputter.output(document, new FileOutputStream("foo.xml"));
System.out.println("File creato:");
//Stampo l'output anche sullo standard output
outputter.output(document, System.out);
}
catch (IOException e) {
System.err.println("Errore durante il parsing del documento");
e.printStackTrace();
}
}
Output prodotto:
<?xml version="1.0" encoding="UTF-8"?>
<TODO_LIST>
<ITEM importanza="3" perc_completamento="75" completata="no">
<DESCR>Fare la spesa</DESCR>
</ITEM>
<ITEM importanza="7" perc_completamento="100" completata="si">
<DESCR>Stendere i panni</DESCR>
</ITEM>
<ITEM importanza="4" perc_completamento="0" completata="no">
<DESCR>Cucinare</DESCR>
</ITEM>
</TODO_LIST>
Programma 2: Il reader
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
public class JDOMReader {
public static void main(String[] args) {
try {
//Creo un SAXBuilder e con esco costruisco un document
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("foo.xml"));
//Prendo la radice
Element root = document.getRootElement();
//Estraggo i figli dalla radice
List children = root.getChildren();
Iterator iterator = children.iterator();
//Per ogni figlio
while(iterator.hasNext()){
//Mostro il valore dell'elemento figlio "DESCR" e degli
//attributi "importanza", "perc_completamento", e "completata"
//sullo standard output
Element item = (Element)iterator.next();
Element description = item.getChild("DESCR");
System.out.println("*" + description.getText());
System.out.println("tImportanza: " + item.getAttributeValue("importanza"));
System.out.println("tCompletamento: " + item.getAttributeValue("perc_completamento") + "%");
System.out.println("tItem copmletata: " + item.getAttributeValue("completata")+"n");
}
}
catch (Exception e) {
System.err.println("Errore durante la lettura dal file");
e.printStackTrace();
}
}
Output prodotto:
*Fare la spesa
Importanza: 3
Completamento: 75%
Item copmletata: no
*Stendere i panni
Importanza: 7
Completamento: 100%
Item copmletata: si
*Cucinare
Importanza: 4
Completamento: 0%
Item copmletata: no
Dopo aver letto questi due semplici articoli dovreste essere in grado di utilizzare le principali funzioni per manipolare file XML con Java.