节点对象 - 为空节点对象分配值

时间:2016-12-27 14:12:06

标签: java xml xpath xml-parsing

我正在使用XPath解析XMl文件并使用内容处理java中的数据设置,可能会出现我们可以将空标记作为输入进行处理的情况。

但是当我尝试使用 setNodeValue setTextContent 设置null节点对象的值时,方法仍然会遇到同样的问题。我们是否有任何其他选项来设置null Node对象的值。

    **//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 个答案:

答案 0 :(得分: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);
相关问题