【问题标题】:Node Object - Assign value for a null Node object节点对象 - 为空节点对象赋值
【发布时间】:2016-12-27 14:12:06
【问题描述】:

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

但是当我尝试使用 setNodeValuesetTextContent 方法为空节点对象设置值时,仍然遇到同样的问题。我们是否有任何其他选项来设置 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");

【问题讨论】:

    标签: java xml xpath xml-parsing


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-17
      • 2015-05-08
      • 1970-01-01
      • 2013-09-08
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多