如何在 Java 中使用 XPath 区分这两段 XML?
<iq type="result">
<query xmlns="jabber:iq:roster">
</query>
</iq>
和
<iq type="result">
<query xmlns="vcard-temp">
</query>
</iq>
我试过这个,它总是打印空,
public class Test {
public static void main(String[] args) throws Exception {
final String xml = "<iq type=\"result\"><query xmlns=\"jabber:iq:roster\"></query></iq>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(createInputSource(xml));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
switch (prefix) {
case "roster":
return "jabber:iq:roster";
case "vcard":
return "vcard-temp";
}
return XMLConstants.NULL_NS_URI;
}
@Override
public String getPrefix(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Iterator getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
Node match = (Node) xpath.evaluate("/iq/roster:query", document, XPathConstants.NODE);
System.out.println(match);
}
private static InputSource createInputSource(String xml) {
return new InputSource(new StringReader(xml));
}
}