Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trouble reading back an XML buffer

 
M Burke
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I created a simple XML buffer and I want to read it back. (I'm trying to learn this stuff)

Problem is, when I try to print the node, I get a null.


package test;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;



public class TestXML
{


public static void main(String[] args)
{
protected DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
protected DocumentBuilder builder;
protected Document doc;
protected Element root;

try{

builder = factory.newDocumentBuilder();
doc = builder.newDocument();

root = doc.createElement("Object"); //Create a new node
doc.appendChild(root);// Add the node to the root node

Node item = doc.createElement("item");
item.appendChild(doc.createTextNode("numberField"));
root.appendChild(item);


//Now read it back

NodeList itemlist = doc.getElementsByTagName("item");
int len = itemlist.getLength();
for(int i=0; i < len; ++i){
Node node = itemlist.item(i);
System.out.println(node.getNodeValue());//this prints null
}


} catch (Exception e){
e.printStackTrace();
}

}

}
[ December 16, 2005: Message edited by: M Burke ]
 
Rajagopal Manohar
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by M Burke:

NodeList itemlist = doc.getElementsByTagName("item");
int len = itemlist.getLength();
for(int i=0; i < len; ++i){
Node node = itemlist.item(i);
System.out.println(node.getNodeValue());//this
[ December 16, 2005: Message edited by: M Burke ]


Burke,
This is probably the most common mistake noobs to DOM do (me included)

The funda is that to get the element text we need to get the text node. So modifying you code to node.getFirstChild().getNodeValue() will give you the text node.

If you dont find that very intutive then try JDOM

For more info on Node types and thier values look here http://java.sun.com/j2se/1.4.2/docs/api/org/w3c/dom/Node.html

-Rajagopal
[ December 16, 2005: Message edited by: Rajagopal Manohar ]
 
M Burke
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I appreciate the tip
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic