aspose file tools*
The moose likes XML and Related Technologies and the fly likes Trouble reading back an XML buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Trouble reading back an XML buffer" Watch "Trouble reading back an XML buffer" New topic
Author

Trouble reading back an XML buffer

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 388
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

Joined: Nov 26, 2004
Posts: 183
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

Joined: Jun 25, 2004
Posts: 388
Thanks, I appreciate the tip
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trouble reading back an XML buffer