Cross-Platform, Java

Create XML file with JAVA

If you would like to create an XML file similar to this:

1
2
3
<customers>
<customer id="124587956" firstname="George" lastname="Karpouzas"/>
</customers>

you can do it by using the following JAVA method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void store(Customer customer){
      try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dcb = factory.newDocumentBuilder();            
 
            Document doc = dcb.newDocument();
            Element rootElement = doc.createElement("customers");
            doc.appendChild(rootElement);
 
            Element custel = doc.createElement("customer");
            rootElement.appendChild(custel);
            custel.setAttribute("id", customer.getID()+"");
            custel.setAttribute("firstname", customer.getFirstName());
            custel.setAttribute("lastname", customer.getLastName());
 
            TransformerFactory transformerf = TransformerFactory.newInstance();
            transformerf.setAttribute("indent-number", 4);
            Transformer transformer = transformerf.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
 
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult("xmlfile.xml");
 
            transformer.transform(source, result);
          } catch (ParserConfigurationException pce) {
              System.err.println("Error: " + pce.getMessage());
          } catch (TransformerException tfe) {
              System.err.println("Error: " + tfe.getMessage());
          }
        }

You have to create customer class on your own šŸ˜‰