调用方法比较两个XML节点时。正在发生空指针异常。请帮我提供宝贵的意见。
for (int i = 0; i < englishTextNodes.getLength(); i++)
{
for (int j = 0; j < otrLangTextNode.getLength(); j++)
{
if( englishTextNodes.item(i).getNodeValue().toString().compareToIgnoreCase(
otrLangTextNode.item(j).getNodeValue().toString()) == 0 )
{
Results.add(englishTextNodes.item(i).getNodeValue().toString());
break;
}
}
return Results;
}
添加检查以确保.getNodeValue()调用不会返回null。如果.getNodeValue()返回null,则调用.toString()将引发null指针异常。
您可能需要编写一个比较助手方法,在比较之前考虑空值,并在if语句中调用该方法,以使代码干净。
非常感谢您的宝贵意见。我将方法从getNodeValue()更改为getTextContent(),因为getNodeValue)存储的是null值,所以发生了异常。现在它对我来说运行良好。下面是更改后的代码。
for (int i = 0; i < englishTextNodes.getLength(); i++)
{
for (int j = 0; j < otrLangTextNode.getLength(); j++)
{
if((englishTextNodes.item(i).getTextContent().toString().compareToIgnoreCase(otrLangTextNode.item(j).getTextContent().toString()))==0)
{
Results.add("UntranslatedNodes"+englishTextNodes.item(i).getTextContent().toString());打破}}}