0

I have been trying to use code I found from other posts, to parse an xml string but when trying to get to the node elements I keep getting null values. Can someone see the error or something I am missing?

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder  db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(post));

    Document doc;
    try {

        doc = db.parse(is);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        NodeList nodes = root.getElementsByTagName("entry");


    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

the root element is null and nodelist null as well. The XML post starts with:

<entry xmlns="http://www.w3.org/2005/Atom" 
xmlns:activity="http://activitystrea.ms/spec/
1.0/"    xmlns:service="http://activitystrea.ms/ 
service-provider"    xmlns:thr="http://purl.org/syndication/thread/1.0" 
xmlns:gnip="http://www.post.com/schemas/2010" 
 xmlns:geo="http://www.georss.org/georss" xmlns:poco="http://portablecontacts.net/spec/1.0">
 <id>...

EDIT:

NodeList nodes.. //The value of the local nodes is not used
[entry: null]  
// it skips the following lines...
for(int i=0; i < nodes.getLength() - 1; i++){
        System.out.println(nodes.item(i).toString());   
        }
6
  • Can you post the exception stacktrace? Commented Aug 25, 2014 at 20:18
  • What does "keep getting null values" mean? What variable in your code is null? Commented Aug 25, 2014 at 20:27
  • I was debugging and looking at the values for the nodelist above and root element; will post the values now. Commented Aug 25, 2014 at 20:28
  • IMO, you need to give the Node name @ root.getElementsByTagName("entry"); Instead of entry, try the actual node name.. look at this post.. mkyong.com/java/how-to-read-xml-file-in-java-dom-parser Commented Aug 25, 2014 at 20:58
  • The other thing which I m not clear is, I guess you are using DOM Parser. why do you catch SAXException ??? Commented Aug 25, 2014 at 21:15

1 Answer 1

2

replace NodeList nodes = root.getElementsByTagName("entry");

by NodeList nodes = root.getChildNodes();

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I did figure that out but will credit you as I am unable to credit Vikram above whose response was helpful.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.