Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. import org.jdom2.Attribute;
  2. import org.jdom2.Document;
  3. import org.jdom2.Element;
  4. import org.jdom2.JDOMException;
  5. import org.jdom2.input.SAXBuilder;
  6. import org.jdom2.output.Format;
  7. import org.jdom2.output.XMLOutputter;
  8.  
  9. import java.io.File;
  10. import java.io.FileInputStream;
  11. import java.io.FileWriter;
  12. import java.io.IOException;
  13.  
  14. public class WriteXml2 {
  15.     public static void Writer() throws JDOMException, IOException {
  16.  
  17.         Document document = null;
  18.         Element root = null;
  19.  
  20.         File xmlFile = new File("test.xml");
  21.         if(xmlFile.exists()) {
  22.             // try to load document from xml file if it exist
  23.             // create a file input stream
  24.             FileInputStream fis = new FileInputStream(xmlFile);
  25.             // create a sax builder to parse the document
  26.             SAXBuilder sb = new SAXBuilder();
  27.             // parse the xml content provided by the file input stream and create a Document object
  28.             document = sb.build(fis);
  29.             // get the root element of the document
  30.             root = document.getRootElement();
  31.             fis.close();
  32.         } else {
  33.             // if it does not exist create a new document and new root
  34.             document = new Document();
  35.             root = new Element("productlist");
  36.         }
  37.  
  38.         String nom = "linux";
  39.         String ref = "F598";
  40.         String date_deb = "20 jan 2020";
  41.         String date_fin = "20 sep 2020";
  42.         String nb_heurs = "350";
  43.         String ens = "salouha";
  44.         Element child = new Element("Formation");
  45.         child.setAttribute(new Attribute("ref", ref));
  46.         child.addContent(new Element("nom").setText(nom));
  47.         child.addContent(new Element("date_deb").setText(date_deb));
  48.         child.addContent(new Element("date_fin").setText(date_fin));
  49.         child.addContent(new Element("nb_heurs").setText(nb_heurs));
  50.  
  51.         root.addContent(child);
  52.         document.setContent(root);
  53.         try {
  54.             FileWriter writer = new FileWriter("test.xml");
  55.             XMLOutputter outputter = new XMLOutputter();
  56.             outputter.setFormat(Format.getPrettyFormat());
  57.             outputter.output(document, writer);
  58.             outputter.output(document, System.out);
  59.             writer.close(); // close writer
  60.         } catch (IOException e) {
  61.             e.printStackTrace();
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement