import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerException; import javax.xml.transform.OutputKeys; class Program02 { private static Document buildDoc() { Document doc = null; try { doc = tryBuildDoc(); }catch(ParserConfigurationException ex) { System.err.println("Hiba a dokumentum létrehozása során!"); } return doc; } private static Document tryBuildDoc() throws ParserConfigurationException{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); return doc; } private static void createXml(Document doc) { Element root = doc.createElement("vallalat"); doc.appendChild(root); Element dolgozo = doc.createElement("dolgozo"); root.appendChild(dolgozo); Attr attr = doc.createAttribute("id"); attr.setValue("1"); dolgozo.setAttributeNode(attr); Element nev = doc.createElement("nev"); nev.appendChild(doc.createTextNode("Nagy Mihály")); dolgozo.appendChild(nev); Element telepules = doc.createElement("telepules"); telepules.appendChild(doc.createTextNode("Szolnok")); dolgozo.appendChild(telepules); Element fizetes = doc.createElement("fizetes"); fizetes.appendChild(doc.createTextNode("845000")); dolgozo.appendChild(fizetes); } private static void writeXml(Document doc) { try { tryWriteXml(doc); }catch(TransformerConfigurationException ex) { System.err.println("Hiba az XML létrehozása során!"); }catch(TransformerException ex) { System.err.println("Hiba az átalakítás során!"); } } private static void tryWriteXml(Document doc) throws TransformerConfigurationException, TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult("vallalat.xml"); //~ StreamResult result = new StreamResult(System.out); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); t.transform(source, result); } public static void main(String[] args) { Document doc = buildDoc(); createXml(doc); writeXml(doc); System.out.println("A xml fájl készítés vége."); } }