Search code examples
javaxmldomjavax.xml

DocumentBuilder doc (with root element) outputs null even though root element is appended


I'm attempting to have it return my empty root element with attributes but am getting [#document: null] output. Am I absolutely required to have a child element for the root?

String docDate = "1";
String docNumber = "1";
String orderType = "1";
String transactionType = "1";

try {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    Document doc = docBuilder.newDocument();

    Element rootElement = doc.createElement("InvoiceRequest");

    Attr attr = doc.createAttribute("documentDate");
    attr.setValue(docDate);
    rootElement.setAttributeNode(attr);

    Attr attr2 = doc.createAttribute("documentNumber");
    attr2.setValue(docNumber);
    rootElement.setAttributeNode(attr2);

    Attr attr3 = doc.createAttribute("orderType");
    attr3.setValue(orderType);
    rootElement.setAttributeNode(attr3);

    Attr attr4 = doc.createAttribute("transactionType");
    attr4.setValue(transactionType);
    rootElement.setAttributeNode(attr4);

    doc.appendChild(rootElement);
    System.out.println("doc: " + doc.toString());
} catch (Exception e) { 
    e.printStackTrace();
}

Solution

  • DocumentImpl is a subclass of NodeImpl, whose toString() implementation reads:

    public String toString() {
        return "["+getNodeName()+": "+getNodeValue()+"]";
    }
    

    getNodeName() returns #document (which makes sense) - this is defined in CoreDocumentImpl. getNodeValue() returns null because it is not overridden. This behaviour is even mentioned in the Node documentation:

    In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment ), this returns null.

    Because your root element is not included in either getNodeName() or getNodeValue(), it might look empty. But there's nothing to worry about. You need other methods to render the document as an XML string.