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

<document>
<Word>apple</Word>
<Word>hat</Word>
<Word>car</Word>
</document>

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++) {
                            System.out.println((Element)list.item(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??

Recommended Answers

All 3 Replies

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>"+
                    "<Word>apple</Word>"+
                    "<Word>hat</Word>"+
                    "<Word>car</Word>"+
                    "</document>";
        try{
            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();
                    System.out.println(innerText);
                }
            }
        }catch(Exception e){}

Thanks Phaelax. That makes sense. Thanks for your help! I appreciate it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.