我有一个使用分词器生成的单词列表,这些单词都有一个数字引用,即:Rottweiler = n#10001
我还有一个 xml 文件,可以用它来查找罗威纳犬属于狗类别。
然而,其中一些单词的 id 不在 xml 文件中,我想做的是,如果 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
}
还有其他流控制语句,例如 break
、return
甚至标签,您可以使用它们来避免此陷阱。
关于java - xpath 和 java 如果没有 id 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20894034/