Coding the XmlUtil class

Let's now add the first of two methods to the  XmlUtil--a loadXmlFile() method that takes in an XML filename as a String, parses it, and returns an XML document object.

The code involves opening the file to get a File object. Then, using the DOM XML API, we create a DocumentBuilderFactory. With that, we create a new DocumentBuilder. And with that, we parse the input file.

The following is the method in its entirety:

    public Document loadXmlFile(String fileName) throws
ParserConfigurationException, SAXException, IOException { File inputFile = new File(fileName); DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); return doc; }

Note the exceptions that the method throws. The three exceptions are a result of using the File API to open the file and the XML API to parse it. Rather than have the method catch the exception, which it wouldn't really know what to do with, it throws them. These exceptions have an interesting implication to modularity that we'll look at shortly.

The second method is getElement(), which takes in an XML node and the element name to return the value of that element in the node. If no value is found, an empty string is returned. This is all XML API specific and not too interesting for us in the context of this chapter, so here's the method in its entirety:

    public String getElement(Node nNode, String tagName) { 
      if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
        Element eElement = (Element) nNode; 
        return eElement.getElementsByTagName(tagName)
.item(0).getTextContent(); } return ""; }

With this, we are done with XmlUtil. We'll now move on to the more interesting ContactLoader class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.8