4

Im new in Java, and i have a task to Parse one xml file using http with current url http://belbooner.site40.net/testXmls/details.xml

I created Some class to parse it using Dom method, but im having java.lang.NullPointerException while trying to get one Nodes value So here's the code

import java.security.KeyStore.Builder;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.swing.text.Document;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.*;
import org.w3c.dom.CharacterData;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class RequestResponse {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
        RequestResponse req= new RequestResponse();
        req.getHTTPXml(url);
    }

     void getHTTPXml(URL url) throws ParserConfigurationException, IOException, SAXException {

                //URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("ACCEPT","application/xml");
                InputStream xml = conn.getInputStream();


                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                org.w3c.dom.Document document = builder.parse(xml);

                System.out.println(document);
                String doctype = conn.getContentType(); 
                System.out.print(doctype);

                NodeList root = document.getChildNodes();

                Node server = getNodes("server",root);
                Node check = getNodes("check", server.getChildNodes());
                NodeList nodes = check.getChildNodes();

                String checkid= getNodeValue("checkid", nodes);
                System.out.println(checkid);


                conn.disconnect();  

                //return (Document) DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml);


     }


    Node getNodes(String tagName, NodeList nodes) {
        for(int i=0; i< nodes.getLength();i++) {
            Node node= nodes.item(i);
            if(node.getNodeName().equalsIgnoreCase(tagName)) {
                return node;
            }

        }
        return null;
    }

    String getNodeValue(String tagName, NodeList nodes ) {
        for ( int i = 0; i < nodes.getLength(); i++ ) {
            Node node = nodes.item(i);
            if (node.getNodeName().equalsIgnoreCase(tagName)) {
                NodeList childNodes = node.getChildNodes();
                for (int y = 0; y < childNodes.getLength(); y++ ) {
                     Node data = childNodes.item(y);
                     if ( data.getNodeType() == Node.TEXT_NODE ) {
                         return data.getNodeValue();
                     }
                     if(data instanceof CharacterData) {
                         CharacterData cd= (CharacterData) data;
                         return cd.getData();
                     }
                 }

            }
        }
        return "";
    }








    }

The stacktrace I'm getting is the following:

application/xmlException in thread "main" java.lang.NullPointerException at 
RequestResponse.getHTTPXml(RequestResponse.java:45) at
RequestResponse.main(RequestResponse.java:22)

After changin Node server = getNodes("server",root); to `

    Node resultNode = getNodes("result", root);
    Node server = getNodes("server", resultNode.getChildNodes());`

   `application/xmlException in thread "main" java.lang.NullPointerException
        at RequestResponse.getHTTPXml(RequestResponse.java:49)
        at RequestResponse.main(RequestResponse.java:22)

`

Please help me to find the issue.

5
  • 3
    It would be helpful if you could include the stacktrace of the NullPointerException in the question. Nov 30, 2012 at 8:29
  • could you share the line where you are getting the null pointer Nov 30, 2012 at 8:30
  • application/xmlException in thread "main" java.lang.NullPointerException at RequestResponse.getHTTPXml(RequestResponse.java:45) at RequestResponse.main(RequestResponse.java:22)
    – Arshak92
    Nov 30, 2012 at 8:32
  • Please print the error stack trace Nov 30, 2012 at 8:37
  • @Arshak92 : I've edited the post for you to add the stacktrace to the question and also answered you.
    – pabrantes
    Nov 30, 2012 at 8:45

2 Answers 2

3

The problem is that Node server = getNodes("server",root); is returning null.

Why does this happen? Well look how you implemented getNodes

Node getNodes(String tagName, NodeList nodes) {
    for(int i=0; i< nodes.getLength();i++) {
        Node node= nodes.item(i);
        if(node.getNodeName().equalsIgnoreCase(tagName)) {
            return node;
        }
    }
    return null;
}

You are giving as input the document root which is a single "Result" node, you iterate through it and you compare if the node's name is in this case "server" which never will be, hence you return null and get a NPE.

Your node look up must be done in the following way:

 NodeList root = document.getChildNodes();
// Keep in mind that you have the following structure:
// result
//   server
//    checks
//     check
//      checkId
//     check
//      checkId

Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());
Node checks = getNodes("checks", server.getChildNodes());
NodeList childNodes = checks.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
    Node possibleCheck = childNodes.item(i);
    if (possibleCheck.getNodeName().equals("check")) {
    String checkid = getNodeValue("checkid", possibleCheck.getChildNodes());
    System.out.println(checkid);
    }
}

This way you'll be iterating through the correct node list.

7
  • I cant change to root.getChildNodes() as its not a proper Node, maybe you wanted to say NodeList As you see there is another NodeList called root, and i cant take NodeList from NodeList
    – Arshak92
    Nov 30, 2012 at 8:53
  • @Arshak92: you're right, sorry, I was seeing root has a "Node". I've editted my answer
    – pabrantes
    Nov 30, 2012 at 8:57
  • Thank you, but im having another exception application/xmlException in thread "main" java.lang.NullPointerException at RequestResponse.getHTTPXml(RequestResponse.java:48) at RequestResponse.main(RequestResponse.java:22)
    – Arshak92
    Nov 30, 2012 at 9:03
  • I think the problem is in the method getNodes that causing such exception, I'll focus on it
    – Arshak92
    Nov 30, 2012 at 9:05
  • @Arshak92: re-edit your question to add the updated coded along with the updated exception so I or any other stackoverflow member can help you. Also you should unaccept my answer until I've fully helped you.
    – pabrantes
    Nov 30, 2012 at 9:06
2

Using XPath is more efficient and flexible (than normal iteration) while parsing xml.

XPath Tutorial from IBM
XPath Reference Orielly tutorial
Xpath Reference Oracle java tutorial

Try below code.

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RequestResponse {
    public static void main(String[] args) throws ParserConfigurationException,
            IOException, SAXException {
        URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
        RequestResponse req = new RequestResponse();
        req.getHTTPXml(url);
    }

    void getHTTPXml(URL url) throws ParserConfigurationException, IOException,
            SAXException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("ACCEPT", "application/xml");
        InputStream xml = conn.getInputStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(xml);

        System.out.println(document);
        String doctype = conn.getContentType();
        System.out.println(doctype);

        XPathFactory pathFactory = XPathFactory.newInstance();
        XPath path = pathFactory.newXPath();
        XPathExpression expression;
        try {
            expression = path.compile("/result/server/checks/check/checkid");
            NodeList nodeList = (NodeList) expression.evaluate(document,
                    XPathConstants.NODESET);

            String checkids[] = getNodeValue(nodeList);
            for (String checkid : checkids) {
                System.out.print(checkid + ", ");
            }

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        conn.disconnect();

    }

    String[] getNodeValue(NodeList nodes) {
        String checkIds[] = new String[nodes.getLength()];
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            checkIds[i] = node.getTextContent();
        }
        return checkIds;
    }

} 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.