Reputation: 197
I am trying to build the following XML structure:
<EDIOrderPackage xmlns="urn:URI" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Version>1.0.0.0</Version>
<Test>true</Test>
</EDIOrderPackage>
I use JDOM2 and don't know how to add 2 Namespaces!
Even if I set only one Namespace the result is not the same as I wish it to be.
If I set the Namespace by root.setNamespace()
and use the 2nd one with the prefix i it looks like this:
<i:EDIOrderPackage mlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Version>1.0.0.0</Version>
<Test>true</Test>
<i:/EDIOrderPackage>
So there is an i before the EDIPOrderPackage.
If i dont use a prefix is looks like this:
<EDIOrderPackage xmlns="urn:URI">
<Version xmlns="">1.0.0.0</Version>
<Test xmlns="">true</Test>
</EDIOrderPackage>
If if try to add it as attributes, it throws the error message that I cannot an attribute with the name "xmlns"
So how can I build an XML with JDOM looking like the one above?
Upvotes: 4
Views: 1187
Reputation: 17707
The trick is that, with Namespaces, you have to specify it correctly for all elements you add.
Additionally, a default Namespace is one that is declared as xmlns="...."
and not xmlns:abc="...."
When you use a default namespace, it has no 'prefix' on the elements. So from your example code you have:
xmlns="urn:URI"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
You can create these with JDOM as:
Namespace nsDefault = Namespace.getNamespace("urn:URI");
Namespace nsI = Namespace.getNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
Now, when you create your elements, you have to put them in the right Namespaces:
Element root = new Element("EDIOrderPackage", nsDefault);
Element version = new Element("Version", nsDefault);
Element test = new Element("Test", nsDefault);
root.addNamespaceDeclaration(nsI); // add the i namespace declaration.
root.addContent(version);
root.addContent(test);
If you add the XMLOutputter aspect of things:
Document doc = new Document(root);
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(doc, System.out);
the above code produces the output
<?xml version="1.0" encoding="UTF-8"?>
<EDIOrderPackage xmlns="urn:URI" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Version />
<Test />
</EDIOrderPackage>
Upvotes: 4