我想使用xPath检查我的xml文件中是否存在code = "ABC"
。您能为我建议一些方法吗?
<metadata>
<codes class = "class1">
<code code = "ABC">
<detail "blah blah"/>
</code>
</codes>
<codes class = "class2">
<code code = "123">
<detail "blah blah"/>
</code>
</codes>
</metadata>
[编辑] 我做了以下。它重新出现了。
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//codes/code[@ code ='ABC']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: "+ nodes.item(i).getNodeValue());
}
答案 0 :(得分:4)
我不知道您是如何测试代码的,因为<detail "blah blah"/>
是一个不正确的xml构造,它应该是<detail x="blah blah"/>
,即 name-value 对!!
对于XPath表达式"//codes/code[@ code ='ABC']"
,nodes.item(i).getNodeValue())
将是 null
,因为它将返回一个元素。请参阅以下Javadoc评论:
<强> A working sample:
强>
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Test
{
public static void main(String[] args) throws Exception
{
Document doc = getDoc();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Have I found anything? " + (nodes.getLength() > 0 ? "Yes": "No"));
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: "+ nodes.item(i).getNodeValue());
}
}
private static Document getDoc()
{
String xml = "<metadata>"+
"<codes class = 'class1'>"+
"<code code='ABC'>"+
"<detail x='blah blah'/>"+
"</code>"+
"</codes>"+
"<codes class = 'class2'>"+
"<code code = '123'>"+
"<detail x='blah blah'/>"+
"</code>"+
"</codes>"+
"</metadata>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new ByteArrayInputStream(xml.getBytes()));
return dom;
}catch(Exception pce) {
pce.printStackTrace();
}
return null;
}
}