Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JAVA中检查空XML元素_Java_Xml Parsing - Fatal编程技术网

如何在JAVA中检查空XML元素

如何在JAVA中检查空XML元素,java,xml-parsing,Java,Xml Parsing,我有一个XML,如下所示: <info> <userId>Admin</userId> <userNotes></userNotes> </info> 但是上面的代码抛出了一个空指针错误,因为userNotes元素为空 关于如何解决这个问题有什么想法吗?(已更正) userNotesNodeList.item(0).getChildNodes().getLength()如果没有子元素或文本

我有一个XML,如下所示:

<info>
    <userId>Admin</userId>
    <userNotes></userNotes>         
</info>
但是上面的代码抛出了一个空指针错误,因为
userNotes
元素为空

关于如何解决这个问题有什么想法吗?

(已更正)

userNotesNodeList.item(0).getChildNodes().getLength()
如果没有子元素或文本,将返回0

为什么

userNotesNodeList
节点的列表。有1个。无论如何,你可以检查长度来验证它

userNotesNodeList。项(0)
是第一个
元素

userNotesNodeList.item(0)。getChildNodes()
中的内容列表

如果没有文本,这是一个包含0个元素的节点列表,因此

userNotesNodeList.item(0).getChildNodes().getLength() should return 0.
我建议对中间结果使用VAR(以使代码更清晰)。或者创建一些帮助器方法来避免这种繁琐的XMLAPI

NodeList userNotesNodeList = document.getElementsByTagName("userNotes");
// userNotesNodeList should not be null, it can be zero length, but not null
Element userNotesElement = (Element) userNotesNodeList.item(0);
if (userNotesElement.getChildNodes().getLength() > 0) // then it has text
{
   userNotes = userNotesElement.getChildNodes().item(0).getNodeValue();
}

您正在对getNodeValue返回的空值调用trim。在调用trim之前检查该方法的结果。
NodeList userNotesNodeList = document.getElementsByTagName("userNotes");
// userNotesNodeList should not be null, it can be zero length, but not null
Element userNotesElement = (Element) userNotesNodeList.item(0);
if (userNotesElement.getChildNodes().getLength() > 0) // then it has text
{
   userNotes = userNotesElement.getChildNodes().item(0).getNodeValue();
}