Solved

XML parsing in Java

Posted on 2014-01-12
6
417 Views
Last Modified: 2014-01-14
How to parse XML below in Java using DOM Parser:
<employees>
  <employee id="111">
    <firstName>Rakesh</firstName>
    <lastName>Mishra</lastName>
    <location>Bangalore</location>
  </employee>
  <employee id="112">
    <firstName>John</firstName>
    <lastName>Davis</lastName>
    <location>Chennai</location>
  </employee>
  <employee id="113">
    <firstName>Rajesh</firstName>
    <lastName>Sharma</lastName>
    <location>Pune</location>
  </employee>
</employees>
0
Comment
Question by:vakils
  • 3
  • 3
6 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 39775815
Where is this XML coming from? A file, a database, the web, or hardcoded in your Java program?  Assuming that this may be in a file, parsing is as simple as this...

DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

Document doc = documentBuilder.parse(new FileInputStream("my_xml_file.xml"));

// Do something useful with "doc"

Open in new window

0
 

Author Comment

by:vakils
ID: 39778527
XML comes from file. Reading nodes value, is what I want. XML elements have no attributes at this stage and some elements may not any have value. For example while traversing XML tree, if an element has no value, I get null pointer exception in element.getTextContent(). Is there a elegant way to know that element has no value, rather than checking if element is null?

XML:
<contracts>
            <contract>123</contract> // OK
             <contract_year></contract_year>        //exception
</contracts>
//Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {

      //We have encountered an <employee> tag.
      Node node = nodeList.item(i);
      if (node instanceof Element) {
        Employee emp = new Employee();
        emp.id = node.getAttributes().
            getNamedItem("id").getNodeValue();

        NodeList childNodes = node.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
          Node cNode = childNodes.item(j);

          //Identifying the child tag of employee encountered.
          if (cNode instanceof Element) {
          String content = cNode.getLastChild().getTextContent().trim();  // null pointer exception if element has no value
0
 

Author Comment

by:vakils
ID: 39778530
XML:
<employee>
            <Name>SAM</Name> // OK
             <Middle></Middle>        //exception
</employee>
//Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {

      //We have encountered an <employee> tag.
      Node node = nodeList.item(i);
      if (node instanceof Element) {
        Employee emp = new Employee();
        emp.id = node.getAttributes().
            getNamedItem("id").getNodeValue();

        NodeList childNodes = node.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
          Node cNode = childNodes.item(j);

          //Identifying the child tag of employee encountered.
          if (cNode instanceof Element) {
         String content = cNode.getLastChild().getTextContent().trim();  // null pointer exception if element has no value
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39780987
Just remove the    .getLastChild()    call from your bold line of code, ie.
String content = cNode.getTextContent().trim();

Open in new window

It was the .getLastChild() method call that is returning a NULL for the empty element and so when you attempt to call  .getTextContent() on a NULL object you get the NullPointerException. Also, I'm pretty sure that .getTextContent() never returns a NULL (at least for Element nodes which are the only ones that you are processing) so calling .trim() on that should be safe.
0
 

Author Comment

by:vakils
ID: 39781067
OK. Got it. Calling trim is OK. getLastChild is not needed.
Thanks!
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39781073
Not a problem, glad to help! :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
tomcat administrtor 12 68
Using jdbcTemplate.batchUpdate to improve INSERT performance 6 27
American Express @Work site and Java 4 68
Java array 21 87
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question