I try to add new <class>
elements to a persistence.xml file with JDOM2.
persistenceUnitEl.add(new Element("class").addContent(className));
The problem is that jdom2 always adds xmlns=""
to the <class>
elements.
How can i prevent this?
removeAttribute("xmlns")
does not work and removeNameSpace(el.getNameSpace())
also does not work.
From my understanding, I think this is what you want.
This is what you get.
Use the below snippet to create the new Element
Here is the full code.
JDOM only adds the
xmlns=""
if you add child elements to other elements that are already in a namespace. The default Namespace in XML is the one which has no prefix. In the following example:There are no namespace prefixes, and the default namespace is "".
The above XML snippet is semantically identical to:
The
xmlns=""
means that, any time you see an element that has no prefix, that you should put it in the 'empty' namespace "".Now, if you want to put things in a namespace, and have a prefix, you would do:
Note that the root and child elements in the above example are in the namespace
http://mynamespace
, and that namespace has the prefixns
. The above code would be semantically identical to (has the same meaning as):In the above example, the default namespace is changed from "" to be
http://mynamespace
, so now elements that have no prefix are in that default namespacehttp://mynamespace
. To reiterate, the following two documents are identical:and
Now, what does all of this have to do with your problem?
Well, your element
persistenceUnitEl
must be in a default namespace that is not "". Somewhere on that element, or on of it's parents, you have something like:In the above, the
PersistenceUnit
is in the namespace...something....
. Now, you are asking JDOM to add the elementnew Element("class")
to the document, so you are getting:The reason is because you are telling JDOM to put it in the "" namespace (Namespace.NO_NAMESPACE). See the documentation for JDOM here:
new Element(String name)
.instead, what you want to do, is put it in the same namespace as the parent:
Now, the real question is whether the "class" element actually belongs in the same namespace as the parent, or not. But that is a question only you can answer.
Resources: