Java Data Science Cookbook
上QQ阅读APP看书,第一时间看更新

Parsing XML files using JDOM

Unlike text data, which is often unstructured, organizing data in XML files is a popular method to prepare, convey, and exploit data in a structured way. There are several ways to parse contents of XML files. In this book, we will limit our recipes to an external Java library for XML parsing named JDOM.

Getting ready

In order to perform this recipe, we will require the following:

  1. Download version 2.06 of the JAR file for JDOM from http://www.jdom.org/downloads/index.html.
  2. In Eclipse, create a project and include the JAR file an external JAR.
  3. Open up notepad. Create a new file named xmldummy with the .xml extension. The content of the file will be as simple as follows:
       <?xml version="1.0"?> 
       <book> 
          <author> 
             <firstname>Alice</firstname> 
             <lastname>Peterson</lastname> 
          </author> 
          <author> 
             <firstname>John</firstname> 
             <lastname>Doe</lastname> 
          </author> 
       </book> 

How to do it...

  1. Create a SAXBuilder object named builder:
           SAXBuilder builder = new SAXBuilder(); 
    
  2. Now you need to create a File object to point to the XML file that you will be parsing. If you have saved your XML file in the C:/ drive, then type in the following code segment:
            File file = new File("c:/dummyxml.xml"); 
    
  3. In a try block, you are going to create a Document object, which will be your XML file:
            try { 
              Document document = (Document) builder.build(file); 
    
  4. When you are parsing an XML, as it is tree structured, you need to know the root element of the file to start traversing the tree (in other words, to start parsing systematically). So, you are creating a rootNode object of type Element to hold the root element, which in our example is <book> node:
            Element rootNode = document.getRootElement(); 
    
  5. Then, you will be retrieving all the children nodes of your root node that have the name author. The names come as a list, and therefore, you will be using a list variable to hold them:
            List list = rootNode.getChildren("author"); 
    
  6. Next, you will be iterating over this list using a for loop to get the elements of the entries in this list. Each element will be kept in an Element type variable named node. This variable has a method named getChildText(), which takes the name of its child as parameter; the method returns the textual content of the named child element, or null if there is no such child. This method is convenient because calling getChild().getText() can throw a NullPointerException:
            for (int i = 0; i < list.size(); i++) { 
               Element node = (Element) list.get(i); 
            System.out.println("First Name : " + 
              node.getChildText("firstname")); 
            System.out.println("Last Name : " +             
              node.getChildText("lastname")); 
            } 
    
  7. Finally, you will be closing the try block; put the following catch blocks to handle exceptions:
            } catch (IOException io) { 
                  System.out.println(io.getMessage()); 
            } catch (JDOMException jdomex) { 
                  System.out.println(jdomex.getMessage()); 
            }  
    

    The complete code for the recipe is as follows:

    import java.io.File; 
    import java.io.IOException; 
    import java.util.List; 
     
    import org.jdom2.Document; 
    import org.jdom2.Element; 
    import org.jdom2.JDOMException; 
    import org.jdom2.input.SAXBuilder; 
     
    public class TestJdom { 
     
       public static void main(String[] args){ 
          TestJdom test = new TestJdom(); 
          test.parseXml("C:/dummyxml.com"); 
     
       } 
       public void parseXml(String fileName){ 
          SAXBuilder builder = new SAXBuilder(); 
          File file = new File(fileName); 
          try { 
             Document document = (Document) builder.build(file); 
             Element rootNode = document.getRootElement(); 
             List list = rootNode.getChildren("author"); 
             for (int i = 0; i < list.size(); i++) { 
                Element node = (Element) list.get(i); 
                System.out.println("First Name : " + 
                    node.getChildText("firstname")); 
                System.out.println("Last Name : " + 
                    node.getChildText("lastname")); 
             } 
          } catch (IOException io) { 
             System.out.println(io.getMessage()); 
          } catch (JDOMException jdomex) { 
             System.out.println(jdomex.getMessage()); 
          } 
       } 
    } 
    
Note

There are many different types of XML parsers, and each has its own benefits Dom Parser: These parsers load the complete content of the document in memory and create its complete hierarchical tree in memory. SAX Parser: These parsers do not load the complete document into the memory and parse the documents on event-based triggers. JDOM Parser: JDOM parsers parse the document in a similar fashion to DOM parser but in a more convenient way. StAX Parser: These parsers handle the document in a similar fashion to SAX parser but in a more efficient way. XPath Parser: These parsers parse the document based on expressions and are used extensively with XSLT. DOM4J Parser: This is a Java library to parse XML, XPath, and XSLT using Java Collections Framework that provides support for DOM, SAX, and JAXP.