vbence
vbence

Reputation: 20343

Binding namespaces in Java's DOM API

Currently I'm adding namespaces to a document the following way:

node.getOwnerDocument().getDocumentElement()
    .setAttribute("xmlns:" + prefix, namespaceURI);

The problem with this method is that...

node.lookupPrefix(namespaceURI);

still returns null.

An other attempt:

node.getOwnerDocument().getDocumentElement()
.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix, namespaceURI);

ends up causing:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

Is there a way that works?

Upvotes: 1

Views: 290

Answers (1)

vbence
vbence

Reputation: 20343

The second attempt was a step into the right direction. The missing part (cause of the exception) was that you have to include xmlns in the attribute. So "ns1" is not valid but "xmlns:ns1" is.

(You can use the constant for the string "xmlns" for beauty points).

node.getOwnerDocument().getDocumentElement().setAttributeNS(
    XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    XMLConstants.XMLNS_ATTRIBUTE + ":" + prefix,
    namespaceURI);

Upvotes: 1

Related Questions