Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.jdom2.Attribute;
- import org.jdom2.Document;
- import org.jdom2.Element;
- import org.jdom2.JDOMException;
- import org.jdom2.input.SAXBuilder;
- import org.jdom2.output.Format;
- import org.jdom2.output.XMLOutputter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- public class WriteXml2 {
- public static void Writer() throws JDOMException, IOException {
- Document document = null;
- Element root = null;
- File xmlFile = new File("test.xml");
- if(xmlFile.exists()) {
- // try to load document from xml file if it exist
- // create a file input stream
- FileInputStream fis = new FileInputStream(xmlFile);
- // create a sax builder to parse the document
- SAXBuilder sb = new SAXBuilder();
- // parse the xml content provided by the file input stream and create a Document object
- document = sb.build(fis);
- // get the root element of the document
- root = document.getRootElement();
- fis.close();
- } else {
- // if it does not exist create a new document and new root
- document = new Document();
- root = new Element("productlist");
- }
- String nom = "linux";
- String ref = "F598";
- String date_deb = "20 jan 2020";
- String date_fin = "20 sep 2020";
- String nb_heurs = "350";
- String ens = "salouha";
- Element child = new Element("Formation");
- child.setAttribute(new Attribute("ref", ref));
- child.addContent(new Element("nom").setText(nom));
- child.addContent(new Element("date_deb").setText(date_deb));
- child.addContent(new Element("date_fin").setText(date_fin));
- child.addContent(new Element("nb_heurs").setText(nb_heurs));
- root.addContent(child);
- document.setContent(root);
- try {
- FileWriter writer = new FileWriter("test.xml");
- XMLOutputter outputter = new XMLOutputter();
- outputter.setFormat(Format.getPrettyFormat());
- outputter.output(document, writer);
- outputter.output(document, System.out);
- writer.close(); // close writer
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement