Java DOM - NULL 指针异常
我正在使用 Java 中的 DOM 解析 XML 文档。数据如下所示:
<nodes totalCount="48" count="10">
<node type="A" id="83" label="label1">
<record>new</record>
<createTime>12345</createTime>
</node>
<node type="A" id="77" label="label2">
<record>new</record>
<createTime>4567</createTime>
</node>
</nodes>
这是我用来解析的代码的相关部分:
Document doc = dBuilder.parse(new InputSource(reader));
doc.getDocumentElement().normalize();
Log.w(TAG, "Dom Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("node");
for (int temp = 0; temp < nList.getLength();temp++) {
Element element = (Element) nList.item(temp);
NodeList time = element.getElementsByTagName("createTime");
Element line = (Element) time.item(0);
String value =getDataFromElement(line);
Log.w(TAG, "Create time: " + value );
}
我的 getDataFromElement 方法是
public static String getDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
我的问题是,它在之后给出了空指针异常 中打印 createTime 的第一个值
在getDataFromElement()
方法
谁能帮我诊断这个问题?
I am parsing an XML document using DOM in Java. The data looks like this:
<nodes totalCount="48" count="10">
<node type="A" id="83" label="label1">
<record>new</record>
<createTime>12345</createTime>
</node>
<node type="A" id="77" label="label2">
<record>new</record>
<createTime>4567</createTime>
</node>
</nodes>
This is the relevant portion of my code that I am using to parse:
Document doc = dBuilder.parse(new InputSource(reader));
doc.getDocumentElement().normalize();
Log.w(TAG, "Dom Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("node");
for (int temp = 0; temp < nList.getLength();temp++) {
Element element = (Element) nList.item(temp);
NodeList time = element.getElementsByTagName("createTime");
Element line = (Element) time.item(0);
String value =getDataFromElement(line);
Log.w(TAG, "Create time: " + value );
}
And my getDataFromElement method is
public static String getDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
My problem is, it gives null pointer exception
after printing the first value of createTime at
getDataFromElement()
method
Can anyone help me diagnose this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当任何“node”元素没有“createTime”元素时,就会发生这种情况
It happens when any "node"-element has no "createTime"-element
使用 try/catch 消除不需要的节点:
Use try/catch to eliminate unwanted nodes: