Reputation: 379
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?
Upvotes: 2
Views: 2384
Reputation: 403481
Given your desired example:
<?xml version="1.0" encoding="UTF-8"?>
<article xmlns="http://www.javaworld.com">
<title>Blah, blah, blah</title>
</article>
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 specify jwNS
for all of your child elements, i.e.
myElement.addContent(new Element("title", jwNS ).setText("Blah, blah, blah"));
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 explicit xnmns=""
attribute in order to override the inheritance of the jwNS
namespace from the <article>
parent.
Upvotes: 4
Reputation: 21419
Try creating your element by using:
Element myElement = new Element("article");
instead of
Element myElement = new Element("article", jwNS);
Upvotes: 0