我是java和android的新手。我有一个XML文件像这样:
<?xml version="1.0" encoding="UTF-8"?>
<SendList>
<listdata>
<name>aaaaaa</name>
<message>xfhjj</message>
<tel>1111222</tel>
<icon>list</icon>
</listdata>
<listdata>
<name>bbbbbbbbb</name>
<message>ghjchjxff</message>
<tel>45885367</tel>
<icon>list</icon>
</listdata>
<listdata>
<name>ccccccc</name>
<message>hkggcckj</message>
<tel>46964788</tel>
<icon>list</icon>
</listdata>
</SendList>
我想删除每个节点,但是使用这段代码我使用的是除了最后一个Node之外我收到Null指针Exception!
Node no = document.getFirstChild();
NodeList nl = no.getChildNodes();
for (int n = 0; n < nl.getLength(); n++) {
Node list = document.getElementsByTagName("listdata").item(n);
NodeList nodes = list.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node element = nodes.item(i);
String t = element.getFirstChild().getTextContent();
if (deleteValueName.equals(t)) { \\deleteValueName for example equal aaaaaa OR bbbbbbbbb
if ("name".equals(element.getNodeName())) {
Node nd = element.getParentNode();
Node ndParent = nd.getParentNode();
ndParent.removeChild(nd);
}
}
}
}
请帮助我!
答案 0 :(得分:0)
您需要移动&#39; document.getElementsByTagName&#39;超出for循环,因为在每个循环之后你有越来越少的元素,所以你最终会得到一个NPE。尝试这样的事情:
NodeList nl = document.getElementsByTagName("listdata");
for (int n = 0; n < nl.getLength(); n++) {
Node list = nl.item(n);
NodeList nodes = list.getChildNodes();
...