I have the following XML example:
xmlns:custom="http://example.com/opensearchextensions/1.0/">
Test
Testing....
My concern is with Query element. It has a Namespace attribute and, in java, you will need a namespaceURI to retrieve the value.
My question is: How would I retrieve the list of namespaces from the root element (in this case, OpenSearchDescription element)? I want the attribute, prefix and namespace URI that I can use to request on Query.
Thanks.
PS: I'm using DOM in java, standard in JSE. I'm willing to move to XPath, if it's possible. The requirement is that only the Java Standard API needs to be used.
解决方案
This might get you started, factory.setNamespaceAware(true) is the key for getting the namespace data after all.
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());
}
}
}
}