DocumentBuilder doc (with root element) outputs null even if root element is added

I am trying to return its empty root element with attributes, but I am getting the output [#document: null]. Am I absolutely required to have a child 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();
}

      

+3


source to share


2 answers


DocumentImpl

is a subclass NodeImpl

whose implementation toString()

says:

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 behavior is even mentioned in the documentation Node

:



In cases where there is no obvious mapping of these attributes for a particular nodeType (for example, nodeValue for an element, or attributes for a comment), it returns null.

Since your root element is not included in getNodeName()

either getNodeValue()

, it may appear empty. But there is nothing to worry about. You need other methods to render the document as XML string.

+1


source


The method toString()

you are using here does nothing, it just returns: -

"["+getNodeName()+": "+getNodeValue()+"]"

This way you get: -



[#document: null] //nodeName as document and null nodevalue

      

Don't worry about it and continue your further processing, you will get your intended result, not NPE

.

0


source







All Articles