我有一个使用标记器的单词列表,它们都有一个数字引用,即:Rottweiler = n#10001

我还有一个xml文件,可以用来发现Rottweiler是类别dog。

但是,其中一些单词的xml文件中没有一个ID,如果ID与xml文件中的任何ID不匹配,我想做的就是让程序移至下一个。现在,如果找不到,我的整个程序就会中断。

这是我到目前为止所拥有的:

String search1 = "11111";
String nodePrefix =  "n#"+search1;

Node theNode = (Node) xpath.evaluate("//*[@id='" + nodePrefix+"']", document, XPathConstants.NODE);
String categ = theNode.getAttributes().getNamedItem("categ").getNodeValue();
System.out.println("Animal "+ nodePrefix + " has category " + categ);
        ...more code

最佳答案

如果表达:

Node theNode = (Node) xpath.evaluate("//*[@id='" + nodePrefix+"']", document, XPathConstants.NODE);


找不到节点,则返回null。因此,在这种情况下您将无法执行任何操作,并且应避免执行其余程序。

Node theNode = (Node) xpath.evaluate("//*[@id='" + nodePrefix+"']", document, XPathConstants.NODE);
if(theNode!=null){
    String categ = theNode.getAttributes().getNamedItem("categ").getNodeValue();
    System.out.println("Animal "+ nodePrefix + " has category " + categ);
            ...more code
}


还有其他流控制语句,例如breakreturn甚至标签,可用于避免这种陷阱。

10-06 05:01
查看更多