I am new to JDOM, and am having trouble creating a document. The problem is that I want
to be able to add Elements that do NOT have the “xmlns” attribute. I am using JDOM 1.1
All of the examples I have found show the output without the “xmlns”. Here is a simple
code fragment, along with its output:
Namespace jwNS = Namespace.getNamespace("http://www.javaworld.com");
Element myElement = new Element("article", jwNS);
Document doc = new Document(myElement);
myElement.addContent(new Element("title").setText("Blah, blah, blah"));
// serialize with two space indents and extra line breaks
try {
//XMLOutputter serializer = new XMLOutputter(" ", true);
XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
serializer.output(doc, System.out);
}
catch (IOException e) {
System.err.println(e);
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<article xmlns="http://www.javaworld.com">
<title xmlns="">Blah, blah, blah</title>
</article>
What I want is to just have
<?xml version="1.0" encoding="UTF-8"?>
<article xmlns="http://www.javaworld.com">
<title>Blah, blah, blah</title>
</article>
Can anyone tell me what I am doing wrong?
Given your desired example:
This means that all child elements of
<article>have the same namespace as<article>, i.e. namespaces are inherited from parents to children. That means you need to specifyjwNSfor all of your child elements, i.e.When rendering the XML output, JDOM should then omit the explicit namespace from
<title>, since it inherits it from<article>.By using just
new Element("title"), you’re saying that you want no namespace on<title>, and so JDOm has to add an explicitxnmns=""attribute in order to override the inheritance of thejwNSnamespace from the<article>parent.