(((This whole section is draft)))

Parsing XML Files with Java

Stuff to parse XML with.

  1. SAX
  2. DOM
  3. jDOM

public class DomParser {
    
    // Tag Names
    private static final String ROOTNODE   = "records";
    private static final String RECORD     = "record";
    private static final String NOTES      = "notes";
    private static final String PHONE      = "phone";
    private static final String EMAIL      = "email";
    private static final String FIRST_NAME = "first";
    private static final String LAST_NAME  = "last";

    public List<UserVo> parseData(InputStream in) {
        List<UserVo> out = new LinkedList<UserVo>();
        try {
            Document doc = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(in);
            Node records = findNodeByName(doc, ROOTNODE);
            NodeList recordList = records.getChildNodes();
            for (int i = 0; i < recordList.getLength(); i++) {
                if (RECORD.equals(recordList.item(i).getNodeName())) {
                    out.add(recordNode2User(recordList.item(i)));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return out;
    }

    private UserVo recordNode2User(Node item) {
        UserVo user = new UserVo();
        Node userPart = findNodeByName(item, LAST_NAME);
        user.setLastName(userPart.getTextContent());
        userPart = findNodeByName(item, FIRST_NAME);
        user.setFirstName(userPart.getTextContent());
        userPart = findNodeByName(item, EMAIL);
        user.setEmail(userPart.getTextContent());
        userPart = findNodeByName(item, PHONE);
        user.setPhone(userPart.getTextContent());
        userPart = findNodeByName(item, NOTES);
        user.setNotes(userPart.getTextContent());
        return user;
    }

    private Node findNodeByName(Node root, String type) {
        Node found = null;
        NodeList nodes = root.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            if (type.equals(nodes.item(i).getNodeName())) {
                found = nodes.item(i);
            }
        }
        return found;
    }

}



Sponsors:

About willCode4Beer