Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Data Science Cookbook

You're reading from   Java Data Science Cookbook Explore the power of MLlib, DL4j, Weka, and more

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781787122536
Length 372 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Rushdi Shams Rushdi Shams
Author Profile Icon Rushdi Shams
Rushdi Shams
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Obtaining and Cleaning Data FREE CHAPTER 2. Indexing and Searching Data 3. Analyzing Data Statistically 4. Learning from Data - Part 1 5. Learning from Data - Part 2 6. Retrieving Information from Text Data 7. Handling Big Data 8. Learn Deeply from Data 9. Visualizing Data

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.

You have been reading a chapter from
Java Data Science Cookbook
Published in: Mar 2017
Publisher: Packt
ISBN-13: 9781787122536
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image