5

I'm trying to create an XML document in Java that contains the following Element:

<project xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2" 
         xmlns:acme="http://www.acme.com/schemas"
         color="blue">

I know how to create the project Node. I also know how to set the color attribute using

element.setAttribute("color", "blue")

Do I set the xmlns and xmlns:acme attributes the same way using setAttribute() or do I do it in some special way since they are namespace attributes?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
  • There are examples for several programming models: http://stackoverflow.com/questions/528312/creating-an-xml-document-using-namespaces-in-java –  Aug 03 '12 at 15:13

5 Answers5

12

I believe that you have to use:

element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:acme", "http://www.acme.com/schemas");
lanoxx
  • 12,249
  • 13
  • 87
  • 142
davidfmatheson
  • 3,539
  • 19
  • 27
1

I do not think below code will serve the question!

myDocument.createElementNS("http://www.imsglobal.org/xsd/ims_qtiasiv1p2","project");

This will create an element as below (using DOM)

<http://www.imsglobal.org/xsd/ims_qtiasiv1p2:project>

So this will not add an namespace attribute to an element. So using DOM we can do something like

Element request = doc.createElement("project");

Attr attr = doc.createAttribute("xmlns");
attr.setValue("http://www.imsglobal.org/xsd/ims_qtiasiv1p2");

request.setAttributeNode(attr);

So it will set the first attribute like below, you can set multiple attributes in the same way

<project xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2>
Harsha
  • 505
  • 5
  • 11
  • See also @Jokster's answer: --- http://stackoverflow.com/questions/10584670/setting-namespaces-and-prefixes-in-a-java-dom-document --- – vlakov Jul 01 '15 at 05:37
1

The short answer is: you do not create xmlns attributes yourself. The Java XML class library automatically creates those. By default, it will auto-create namespace mappings and will choose prefixes based on some internal algorithm. If you don't like the default prefixes assigned by the Java XML serializer, you can control them by creating your own namespace resolver, as explained in this article:

https://www.intertech.com/Blog/jaxb-tutorial-customized-namespace-prefixes-example-using-namespaceprefixmapper/

kimbert
  • 2,376
  • 1
  • 10
  • 20
0

You can simply specify the namespace when you create the elements. For example:

myDocument.createElementNS("http://www.imsglobal.org/xsd/ims_qtiasiv1p2","project");

Then the java DOM libraries will handle your namespace declarations for you.

Dave
  • 143
  • 7
0

The only way that worked for me, in 2019, was using the attr() method:

Element element = doc.createElement("project");
element.attr("xmlns","http://www.imsglobal.org/xsd/ims_qtiasiv1p2");
jgerman
  • 1,143
  • 8
  • 14