Crea sito

Java: XML reading Tutorial (Part 2)

Hello to all! In the last tutorial we have written an xml file that contains a users list with one user stored.
You have certainly see this reasult in your browser (Firefox, Opera,...) but now it's time to read your xml file with java, reading your users in the object user.

It's fast and simply to understand and you can find the code project posted at the end of the page.

All you have to do is expressed by the method readUser that search a user that has the same id that you are searching and set fields of the xmlUser in your code correctly.

 

private void readUser(){
  if(xmlUser.getId() == null){
   throw new NullPointerException("You have passed a null value!");
  }
  boolean founded = false;
        try {
            XmlReader reader = new XmlReader(folderPath + FILE_NAME);
            Node root = reader.getNodeList(TAG_ROOT).item(0);

            NodeList userList = root.getChildNodes();
            for (int i = 0; i < userList.getLength(); i++) {
                Node n = userList.item(i);

                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) n;
                    if (reader.getValueForNode(TAG_ID, e).equals("" + xmlUser.getId())) {
                        String read = reader.getValueForNode(TAG_NAME, e);
                        xmlUser.setName((read.equals(TAG_EMPTY) ? null : read));
                        read = reader.getValueForNode(TAG_SURNAME, e);
                        xmlUser.setSurname((read.equals(TAG_EMPTY) ? null : read));                       
                        founded = true;
                    }
                }
            }
            if (!founded) {
                xmlUser = null;
            }
        } catch (Exception ex){
            xmlUser = null;
        }
}

 

I'm sure that there are best ways to implement it (efficent ways) but I want to give you some tips that you have to grow in your code :)
The XmlReader helps you to connect and interact with your xml file. All you have to do is the reading.
When the textvalue of a node match with your id, you have found the correct User and it's time to read the next fields. You have to read the data stored paying attention to "empty" fields, converting "empty" to null if you find it.

 

That's all for this time,

See you soon,

 Simone

 

P.S: the XmlReader is a class to simplify you the concept of reading and some things.