What is the purpose of setNamespaceAware in Java – DocumentBuilder?

What is the purpose of setNamespaceAware in Java – DocumentBuilder? … here is a solution to the problem.

What is the purpose of setNamespaceAware in Java – DocumentBuilder?

Can anyone tell me under what circumstances setNamespaceAware should be set to true or false

Specifying the parser generated by this code as documented provides support for XML namespaces.

However, if I set it to true, it gets an error for XML tags with namespaces.

DocumentBuilderFactory document_builder_factory = null;
DocumentBuilder builder = null;
document_builder_factory = DocumentBuilderFactory.newInstance();
document_builder_factory.setNamespaceAware(true);

try{
    Text text = new Text();

text.set("<h:test>10</h:test>");
    builder = document_builder_factory.newDocumentBuilder();

Document doc = builder.parse(new InputSource(new StringReader(text.toString())));;
    System.out.println(doc.getElementsByTagName("h:test").item(0).getChildNodes().item(0).getNodeValue());

}catch (Exception e){

}

If setNamespaceAware is set to true, I get the following error.

[Fatal Error] :1:9: The prefix “h” for element “h:test” is not bound.

If I don’t set it, I’ll get the value without error.

Solution

In non-namespace-aware documents, colons are valid characters for node names, so you can have an element .

These elements worked fine until the XML namespace was introduced. Therefore, for backward compatibility, when support for namespaces is introduced, the only way to keep that code working without changing is to set namespace awareness to false by default, because is not legal in namespace-aware documents.

Related Problems and Solutions