如何在 JAVA 中检查空的 XML 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12625374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check for an empty XML element in JAVA
提问by ridermule
I have an XML as follows:
我有一个 XML,如下所示:
<info>
<userId>Admin</userId>
<userNotes></userNotes>
</info>
I am trying to parse this in JAVA. and here is my code snippet:
我正在尝试在 JAVA 中解析它。这是我的代码片段:
NodeList userIdNodeList = document.getElementsByTagName("userId");
if (userIdNodeList!=null) {
userId = userIdNodeList.item(0).getChildNodes().item(0).getNodeValue().trim();
}
NodeList userNotesNodeList = document.getElementsByTagName("userNotes");
if (userNotesNodeList!=null) {
userNotes = userNotesNodeList.item(0).getChildNodes().item(0).getNodeValue().trim();
}
But the above code is throwing a NULL pointer error because the userNotes
element is empty.
但是上面的代码因为userNotes
元素为空而抛出一个NULL指针错误。
Any ideas on how to fix this?
有想法该怎么解决这个吗?
回答by helios
(Corrected)
(更正)
userNotesNodeList.item(0).getChildNodes().getLength()
will return 0 if there are no child elements nor text.
userNotesNodeList.item(0).getChildNodes().getLength()
如果没有子元素或文本,将返回 0。
Why
为什么
userNotesNodeList
is the list of <userNotes>
nodes. There are 1. Anyway you could check the length to verify it.
userNotesNodeList
是<userNotes>
节点列表。有 1. 无论如何你可以检查长度来验证它。
userNotesNodeList.item(0)
is the first <userNotes>
element.
userNotesNodeList.item(0)
是第一个<userNotes>
元素。
userNotesNodeList.item(0).getChildNodes()
is the list of things that are inside <userNotes>...</userNotes>
.
userNotesNodeList.item(0).getChildNodes()
是里面的东西的列表<userNotes>...</userNotes>
。
In case of no text this is a NodeList with 0 elements so
如果没有文本,这是一个包含 0 个元素的 NodeList 所以
userNotesNodeList.item(0).getChildNodes().getLength() should return 0.
I suggest using vars for intermidiate results (to make a clearer code). Or creating some helper methods to avoid this cumbersome XML api.
我建议将 vars 用于中间结果(以使代码更清晰)。或者创建一些辅助方法来避免这个繁琐的 XML api。
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();
}