JavaでXPathを使用してこれら2つのXMLを区別するにはどうすればよいですか?
<iq type="result">
<query xmlns="jabber:iq:roster">
</query>
</iq>
と
<iq type="result">
<query xmlns="vcard-temp">
</query>
</iq>
これを試してみましたが、常にnullが出力されます。
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));
}
}