2016-12-27 75 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);