Crea sito

Java: XML writing Tutorial (Part 1)

There are many ways to store data. You can use DB like mysql, mongodb, postgres, sqlite, or you can use more simply way. When you try to write some data in a file many problems occurs:

- Which lines or position contains the field ?

- How can I put this String, id, int,.. in that file?

XML allows you to avoid them and gives you a free, fast and simply way to do it.

All that you have to do is to create a tags tree, like in the image that I have posted.

In this pic you can see User list defined by the tag that contains one user characterized by some fields (id, name and surname).

In this tutorial we'll create this file with DOM (document object model), a tree based way, to do/read the xml files.

DOM description (Wikipedia.org)

 

For this tutorial, I have created three class:

 - User: the class that contains the fields that characterized a user (id, name and surname)

 - Main: the main class of the project that tests the code to write the xml and that contains the method to store/modify users in users list

 - XmlWriter: a usefull class that I have written to create xml files faster and easily

 

In the Main class we create the file if it not exits and we implement the logical to add and modify a user

(If you want to delete a user, it is simple and you can do as an excercise)

 

private void createFile() throws ParserConfigurationException, TransformerException{
  if (folderPath == null) {
            throw new NullPointerException("You have passed a null path!");
        }
        XmlWriter wr = new XmlWriter();
        Element root = wr.getElement(TAG_ROOT);
        wr.addComment(root, "Users list");
        wr.appendRoot(root);
        wr.commit(folderPath + FILE_NAME);
}

With this code we have created the xml file adding the tags for the users list and a comment related to it.

 

private boolean commitUser(){
  if(xmlUser == null || xmlUser.getId() == null){
   throw new NullPointerException("You have passed a null value!");
  }
  File f = new File(folderPath+FILE_NAME);
  if(!f.exists()){
   try {
    createFile();
   } catch (Exception e) {
    return false;
   }
  }
  boolean found = false;
        XmlWriter wrm;
  try {
   wrm = new XmlWriter(folderPath + FILE_NAME);
  } catch (Exception e) {
   return false;
  }
        Node root = wrm.getDocument().getFirstChild();
        NodeList users = root.getChildNodes();

        for (int i = 0; i < users.getLength(); i++) {
            Node userN = users.item(i);
            if (userN.getNodeName().equals(TAG_USER)) {
                Node prop = userN.getFirstChild();
                if (prop.getTextContent().equals("" + xmlUser.getId())) {
                    //we have found an existing user that matches with the passed id.

                }
            }
        }
        if (!found) {
            //we create and add new user
        }

        try {
   wrm.commit(null);
   return true;
  } catch (TransformerException e) {
   return false;
  }
}

With this code we have implemented the add/modify engine for the users.

 

I hope you'll appreciate,

 Simone

 

P.S.: the XmlWriter is a class that simplify you the xml writening and that contains some methods to create xml trees, with DOM, in an easy way.