简体   繁体   中英

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();
}

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 (eg, 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.

The toString() method which you are using here is doing nothing but just returning:-

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

so correspondingly you are getting :-

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

Don't worry about it & keep on doing your further processing, you will get your intended result and not an NPE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM