Reputation: 1241
I have found that JDOM is a good choice to create xml files, and in my case I need to create one with multiple namespaces like this:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:v="http://www.w3.org/2006/vcard/ns#">
<v:VCard rdf:about="164">
<v:fn />
</v:VCard>
</rdf:RDF>
But I don't know how to define the second namespace into the root element. What I get is this:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<v:VCard xmlns:v="http://www.w3.org/2006/vcard/ns#" rdf:about="164">
<v:fn />
</v:VCard>
</rdf:RDF>
Here is my code:
Namespace rdf = Namespace.getNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
Namespace v = Namespace.getNamespace("v", "http://www.w3.org/2006/vcard/ns#");
Element rootElement = new Element("RDF", rdf);
//rootElement.setAttribute("IdontWantoThis", "IdontWantoThis", v);
Element mainElement = new Element("VCard", v);
mainElement.setAttribute("about", "164", rdf);
Element element = new Element("fn", v);
mainElement.addContent(element);
rootElement.addContent(mainElement);
doc.addContent(rootElement);
If I use the commented line I get this other undesirable thing:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:v="http://www.w3.org/2006/vcard/ns#" v:IdontWantoThis="IdontWantoThis">
<v:VCard rdf:about="164">
<v:fn />
</v:VCard>
</rdf:RDF>
I know that there are some RDF specific libraries for java, but I just want to create a simple xml file, dont want to work with models, ontologies, and so on.
Upvotes: 2
Views: 666
Reputation: 17707
You can declare a namespace on an element even if the element does not need it immediately....
Element rootElement = new Element("RDF", rdf);
rootElement.addNamespaceDeclaration(v);
Upvotes: 1