2

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
mitchmcc
  • 369
  • 3
  • 5
  • 18

2 Answers2

4

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    Three years later, and this still helped me. Thanks for the response. Seems XML isn't as died out as it should be. – PaulBGD Jan 11 '15 at 20:55
0

Try creating your element by using:

Element myElement = new Element("article");

instead of

Element myElement = new Element("article", jwNS);
GETah
  • 20,922
  • 7
  • 61
  • 103