Witam,
Mam problem z dopisywaniem danych do końca pliku XML.
Tworze najpierw plik .xml, dodaję jego właściwości, a przy każdym następnym jego użyciu chciałbym wprowadzać już tylko kolejne dane.
jednak w tym drugim przypadku, po pierwsze zawsze dopisuje się <?xml ?>, a dane są zapisywane w jednej linii (nie tworzą struktury drzewiastej)
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootElement = doc.createElement("pracownicy");
Element childElement = doc.createElement("pracownik");
Element grandChildElement = doc.createElement("imie");
Element grandChildElement2 = doc.createElement("nazwisko");
doc.appendChild(rootElement);
rootElement.appendChild(childElement);
childElement.appendChild(grandChildElement);
childElement.appendChild(grandChildElement2);
grandChildElement.setTextContent(imie);
grandChildElement2.setTextContent(nazwisko);
File f = new File("plik.xml");
TransformerFactory fabrykaTransformacji = TransformerFactory.newInstance();
Transformer t = fabrykaTransformacji.newTransformer();
DOMSource domSource = new DOMSource(doc);
if (!f.exists()) {
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
"http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd");
t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 20000802//EN");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(domSource, new StreamResult(new FileOutputStream(f)));
}
else {
t.transform(domSource, new StreamResult(new FileOutputStream(f, true)));
}
}
catch (ParserConfigurationException ex) {
System.out.println(ex);
}
catch (TransformerConfigurationException ex) {
System.out.println(ex);
}
catch (TransformerException ex) {
System.out.println(ex);
}
catch (FileNotFoundException ex) {
System.out.println(ex);
}