vbNewbie
vbNewbie

Reputation: 3345

parsing xml string in java

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());   
        }

Upvotes: 0

Views: 210

Answers (1)

doubleDai
doubleDai

Reputation: 33

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

by NodeList nodes = root.getChildNodes();

Upvotes: 2

Related Questions