2016-12-27 143 views
1

我正在解析一個XMl文件並使用內容在Java中使用XPath處理數據設置,可能會出現這樣的情況:我們可以將空標記作爲應該處理的輸入。節點對象 - 爲空節點對象分配值

但是當我試圖爲空節點對象與setNodeValuesetTextContent方法仍然得到同樣的問題設定值。我們有沒有其他選項可以爲空節點對象設置值。

**//Code Snippet:** 
Node title = XPathAPI.selectSingleNode("Input Node", "title/text()"); 
// *Here if there is no input title tag, then the title variable would be null* 
title.setNodeValue("Value to set on the null node"); 

回答

1

如果titlenull那麼你就不能調用一個方法就可以了。這將導致NullPointerException。您需要先創建並添加一個新節點,然後在新節點上調用setNodeValue。例如。

// your xml document 
Document document = ...; 

// create a new node to add 
Node titleNode = document.createElement("title"); 
titleNode.setNodeValue("Value to set on the null node"); 

// The node named "Input Node" in document 
Node inputNode = ...; 

// append the new node to "Input Node" 
inputNode.appendChild(titleNode);