Retrieving namespaces from an element in Java (using the DOM)

I have the following XML example:

<?xml version="1.0" encoding="UTF-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:custom="http://example.com/opensearchextensions/1.0/"> <ShortName>Test</ShortName> <Description>Testing....</Description> <Url template="whatever" type="what" /> <Query custom:color="blue" role="example" /> </OpenSearchDescription> 

I am concerned about the Query element. It has a namespace attribute and in java you need namespaceURI to get the value.

My question is: how do I get a list of namespaces from the root element (in this case, the OpenSearchDescription element)? I need the attribute, prefix, and namespace URI that I can use to query Query .

Thanks.

PS: I use the DOM in Java, standard in Java SE. I am ready to move to XPath, if possible. The requirement is that you only use the Java Standard API.

+7
source share
2 answers

This may get you started, factory.setNamespaceAware(true) is the key to getting namespace data in the end.

 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(args[0])); Element root = doc.getDocumentElement(); //prints root name space printAttributesInfo((Node) root); NodeList childNodes = root.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { printAttributesInfo(childNodes.item(i)); } } public static void printAttributesInfo(Node root) { NamedNodeMap attributes = root.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node node = attributes.item(i); if (node.getNodeType() == Node.ATTRIBUTE_NODE) { String name = node.getNodeName(); System.out.println(name + " " + node.getNamespaceURI()); } } } } 
+14
source

I don’t know if this is suitable, but what you can do is just take the attributes on the OpenSearchDescription , find out if they are a namespace declaration using the constants located in javax.xml.XMLConstants , for example. XMLNS_ATTRIBUTE constant must be "xmlns". You can traverse all attributes and save all attributes starting with this value as your NameSpaceUri.

I think you should also take a look at NameSpaceContext . I don’t know how you load the document, but if you use XMLStreamReader , you can extract from it a NameSpaceContext that contains exactly the information that you need. Here you can see where you can find NameSpaceContext other ways.

Hope this helps.

0
source

All Articles