tags:

views:

81

answers:

2

I'm trying to build an XML representation of some data. I've followed other examples, but I can't get it working. I've commented code down to this basic bit, and still nothing. This code compiles and runs OK, but the resulting output is empty. A call to dDoc.getDocumentElement() returns null. What am I doing wrong?

Please help me, Stack Overflow. You're my only hope.

        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
        dFactory.setValidating( false );
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
        Document dDoc = dBuilder.newDocument();

        // The root document element.
        Element pageDataElement = dDoc.createElement("page-data");
        pageDataElement.appendChild(dDoc.createTextNode("Example Text."));

        dDoc.appendChild(pageDataElement);

        log.debug(dDoc.getTextContent());
+3  A: 

The following runs ok. You just need to call dDoc.getDocumentElement().getTextContent() instead of dDoc.getTextContent().

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); 
        dFactory.setValidating( false ); 
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); 
        Document dDoc = dBuilder.newDocument(); 

        // The root document element. 
        Element pageDataElement = dDoc.createElement("page-data"); 
        pageDataElement.appendChild(dDoc.createTextNode("Example Text.")); 

        dDoc.appendChild(pageDataElement); 

        System.out.println(dDoc.getDocumentElement().getTextContent());
    }
}

Will give the output:

Example Text.

Blaise Doughan
Yup. I'm not sure why I thought getDocumentElement was returning null. It's not, with just this code. Will accept in 8 mins
iandisme
Has it been 8 mins yet? :)
Blaise Doughan
Sorry for the wait... I haven't been visiting SO as often :)
iandisme