Setting Namespace Attributes on an Element

20,591

Solution 1

I believe that you have to use:

element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:acme", "http://www.acme.com/schemas");

Solution 2

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/

Solution 3

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>
Share:
20,591
JanusFox81
Author by

JanusFox81

I am interested in functional programming. I am also interested in music programming, such as in ChucK or impromptu. My favorite language is Lisp.

Updated on July 12, 2022

Comments

  • JanusFox81
    JanusFox81 almost 2 years

    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?