Samiron
Samiron

Reputation: 5317

Reducing code redundancy while creating XML with XOM

I am using XOM as my XML parsing library. And i am using this for creating XML also. Below is the scenario described with example.

Scenario:

Code:

Element root =  new Element("atom:entry", "http://www.w3c.org/Atom");
Element city = new Element("info:city", "http://www.myinfo.com/Info");
city.appendChild("My City");
root.appendChild(city);     
Document d = new Document(root);
System.out.println(d.toXML());

Generated XML:

<?xml version="1.0"?>
<atom:entry xmlns:atom="http://www.w3c.org/Atom">
   <info:city xmlns:info="http://www.myinfo.com/Info">
       My City
   </info:city>
</atom:entry>

Notice in the XML that here info namespace is added with the node itself. But I need this to be added in root element. like below

<?xml version="1.0"?>
<atom:entry xmlns:atom="http://www.w3c.org/Atom" xmlns:info="http://www.myinfo.com/Info">
   <info:city>
       My City
   </info:city>
</atom:entry>

And to do that, i just need following piece of code

Element root =  new Element("atom:entry", "http://www.w3c.org/Atom");
=> root.addNamespaceDeclaration("info", "http://www.myinfo.com/Info");
Element city = new Element("info:city", "http://www.myinfo.com/Info");
... ... ...

Problem is here i had to add http://www.myinfo.com/Info twice. And in my case there are hundreds of namespaces. So there will so too much redendancy. Is there any way to get rid of this redundancy?

Upvotes: 0

Views: 208

Answers (1)

Elliotte Rusty Harold
Elliotte Rusty Harold

Reputation: 991

No, there is no way to get rid of this redundancy and that's a deliberate decision. In XOM the namespace is a fundamental part of the element itself, not a function of its position in the document.

Of course you could always declare a named constant for the namespace URI.

Upvotes: 1

Related Questions