3

I want to create an XML with a default namespace using DOM:

   <?xml version="1.0" encoding="US-ASCII"?>
<test xmlns="example:ns:uri" attr1="XXX" attr2="YYY">
  <el>bla bla</el>
</test>

I have the following

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
resultingDOMDocument = db.newDocument();
Element rootElement =
   resultingDOMDocument.createElementNS("example:ns:uri", "test-results-upload");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "example:ns:uri");
rootElement.setAttributeNS("example:ns:uri", "attr1", "XXX");
rootElement.setAttributeNS("example:ns:uri", "attr2", "YYY");

And I am getting

<?xml version="1.0" encoding="US-ASCII"?>
<test xmlns="example:ns:uri" ns0:attr1="XXX" xmlns:ns0="example:ns:uri" ns1:attr2="YYY" xmlns:ns1="example:ns:uri">
  <el>bla bla</el>
</test>

I am using standard DOM API in the JDK v6. What am I doing wrong ? I want to underline - I want to use the default namespace and I DON'T want to use namespace prefixes.

Marcin Cinik
  • 131
  • 2
  • 4

1 Answers1

5

I want to use the default namespace and I DON'T want to use namespace prefixes

The default namespace declaration (xmlns="...") only applies to elements, not to attributes. Therefore if you create an attribute in a namespace then the serializer must bind that namespace URI to a prefix and use that prefix for the attribute in order to serialize the DOM tree accurately, even if the same URI is also bound to the default xmlns. Unprefixed attribute names always mean no namespace, so in order to generate

<?xml version="1.0" encoding="US-ASCII"?>
<test xmlns="example:ns:uri" attr1="XXX" attr2="YYY">
  <el>bla bla</el>
</test>

you need to put the elements in the namespace

Element rootElement =
   resultingDOMDocument.createElementNS("example:ns:uri", "test-results-upload");

but the attributes not:

rootElement.setAttributeNS(null, "attr1", "XXX");
rootElement.setAttributeNS(null, "attr2", "YYY");
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • 1
    Thank You IAN - your answer is very useful - I must admit that I wasn't aware of that important fact. Here is the link [http://www.w3.org/TR/REC-xml-names/#defaulting] to XML spec and another answer [http://stackoverflow.com/questions/41561/xml-namespaces-and-attributes] – Marcin Cinik Aug 21 '13 at 07:36