I want to get all the namespaces in the xml file for example
basically problem is to to search using xpath based on namespaces and for that purpose i have to use setNamespaceContext
and don't know namespaces value because it will be on runtime while parsing file.
xpath.setNamespaceContext(namespaces);
public class SimpleNamespaceContext implements NamespaceContext {
private final Map<String, String> PREF_MAP = new HashMap<String, String>();
public SimpleNamespaceContext(final Map<String, String> prefMap) {
PREF_MAP.putAll(prefMap);
}
public String getNamespaceURI(String prefix) {
return PREF_MAP.get(prefix);
}
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
}
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
HashMap<String, String> prefMap = new HashMap<String, String>() {{
put("main", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
put("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
}};
SimpleNamespaceContext namespaces = new SimpleNamespaceContext(prefMap);
xpath.setNamespaceContext(namespaces);
XPathExpression expr = xpath
.compile("/main:workbook/main:sheets/main:sheet[1]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
reference link [How to query XML using namespaces in Java with XPath?
To implement above mention reference i need to get all namespaces query i am using to get all namespaces using xpath is
try {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//namespace::*");
NodeList a = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println(a.getLength());
} catch (Exception e) {
Utility.consoleInfo(e);
}
but this always return nodelist of size 0 . Am i going in wrong direction to achieve this? or what else would be the solution to this problem ?
Summary How should i get all namespaces so that it can be used in xpath ?
please help me in this regard