The xmlns="..."
declaration means that the Document
element (and all its descendants) are in the specified namespace, so you won't get any match for /Document
because that only selects elements named Document
that are not in a namespace - and you can't declare a prefix for the right namespace because the "right namespace" is what you are trying to find out in the first place!
But you don't need XPath to do this - you already have
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
This is a non-namespace-aware DOM tree of the original document (because DocumentBuilderFactory
is not namespace aware by default), in which xmlns
is treated as an attribute, so you can get the value using
String xmlnsVal = doc.getDocumentElement().getAttribute("xmlns");
String lastSegment = xmlnsVal.substring(xmlnsVal.lastIndexOf(':') + 1);
// this is safe even if xmlnsVal doesn't contain any colons - lastIndexOf
// will return -1, so substring(0) is the whole xmlnsVal
If you were parsing with namespaces enabled, i.e. you'd called documentBuilderFactory.setNamespaceAware(true)
before newDocumentBuilder()
, then you could use
String xmlnsVal = doc.getDocumentElement().getNamespaceURI();