Ho un file XML con questa struttura:
codice:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE commenti SYSTEM "commenti.dtd">
<commenti>
<commento title="Titolo 1">
<utente>Utente 1</utente>
<testo>Commento di Utente 1</testo>
</commento>
</commenti>
Questa classe dovrebbe occuparsi di aprire il file XML, modificarlo aggiungendo un nodo
commento e scrivere le modifiche sul medesimo file.
codice:
public class XMLHandler {
private Document document;
public Document openXML(String path) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(path));
} catch (ParserConfigurationException pce) {
} catch (SAXException se) {
} catch (IOException ioe) {
}
return document;
}
private void writeXML(String path) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "commenti.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(
new DOMSource(document),
new StreamResult(new FileOutputStream(path)));
} catch (TransformerConfigurationException tce) {
} catch (TransformerException te) {
} catch (FileNotFoundException fnfe) {
}
}
public void addComment(String path, String user, String content) {
document = openXML(path);
// Creo gli elementi che costituiscono la struttura del documento XML
Element commento = document.createElement("commento");
Attr title = document.createAttribute("title");
Element utente = document.createElement("utente");
Element testo = document.createElement("testo");
// Appendo il nome dall'utente, passato come parametro al metodo
utente.appendChild(document.createTextNode(user));
// Appendo il messaggio scritto dall'utente, passato come parametro al metodo
testo.appendChild(document.createTextNode(content));
// Appendo l'attributo title al commento
title.setValue("Titolo di prova");
commento.setAttributeNode(title);
// Appendo i nodi child
commento.appendChild(utente);
commento.appendChild(testo);
// Scrivo il documento XML
writeXML(path);
}
Il documento viene correttamente aperto e riscritto integralmente (non ricevo eccezioni e la data di modifica del file si aggiorna ogni volta), tuttavia non viene aggiunto alcun nodo commento, il contenuto del document viene lasciato inalterato.
Qualche idea? Grazie.