Hello DaniWeb. Here is my problem. I have an XML file that is arranged like this..


I'm trying to figure out how to grab the actual words.

This is how I'm doing it now.

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new File("data/general/words.xml"));

            NodeList level = doc.getElementsByTagName("document");

                        NodeList list = doc.getElementsByTagName("Word");

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

But it doesn't work. The output it gives me is this:
[Word: null]
[Word: null]
[Word: null]
etc for each element.

So I think what is happening is that it thinks my XML is set up like
<Word name="Apple"/>
<Word name="Car"/>

So I guess my question is how do I grab the word when its inbetween tags instead of a property of a tag??

8 Years
Discussion Span
Last Post by RichardCrickets

It has found the node, but the word itself, i.e. Apple is a child node of the "word" node, a TextNode type.


I was just trying to figure out the same thing last week. Basically, your 'Word' nodes are still Elements with children. To get the text between the opening and closing tags, grab the element's first child node and retrieve its value instead of the parent element's value.

String xml = "<document>"+
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new StringBufferInputStream(xml));

            NodeList nodeList = doc.getElementsByTagName("Word");

            for(int i=0;i<nodeList.getLength();i++){
                if(nodeList.item(i).getNodeType() == Node.ELEMENT_NODE){
                    Element element = (Element)nodeList.item(i);
                    String innerText = element.getFirstChild().getNodeValue().trim();
        }catch(Exception e){}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.