[英]DocumentBuilder doc (with root element) outputs null even though root element is appended
我試圖讓它返回我的空根元素與屬性,但我得到[#document:null]輸出。 我絕對需要為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
是NodeImpl
的子類,其toString()
實現讀取:
public String toString() {
return "["+getNodeName()+": "+getNodeValue()+"]";
}
getNodeName()
返回#document
(這很有意義) - 這是在CoreDocumentImpl
定義的。 getNodeValue()
返回null
因為它未被覆蓋。 在Node
文檔中甚至提到了這種行為:
如果特定nodeType沒有明顯的這些屬性映射(例如,Element的nodeValue或Comment的屬性),則返回null。
由於您的根元素未包含在getNodeName()
或getNodeValue()
,因此它可能看起來是空的。 但沒有什么可擔心的。 您需要其他方法將文檔呈現為XML字符串。
你在這里使用的toString()
方法只是返回: -
"["+getNodeName()+": "+getNodeValue()+"]"
所以相應地你得到: -
[#document: null] //nodeName as document and null nodevalue
不要擔心並繼續進行進一步處理,您將獲得預期的結果,而不是NPE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.