2012-11-28 62 views
0

我正在使用XOM作爲我的XML解析庫。我也用它來創建XML。下面是用例子描述的情景。使用XOM創建XML時減少代碼冗餘

場景:

代碼:

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()); 

生成的XML:在這裏info命名空間添加節點本身的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> 

通知。但是我需要在根元素中添加這個元素。像下面

<?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> 

要做到這一點,我只需要下面的代碼段

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"); 
... ... ... 

問題是在這裏我不得不添加http://www.myinfo.com/Info兩次。在我的情況下,有數百個命名空間。所以會有太多的兌換。有什麼辦法擺脫這種冗餘?

回答

1

不,沒有辦法擺脫這種冗餘,這是一個故意的決定。在XOM中,名稱空間是元素本身的基本組成部分,而不是其在文檔中的位置功能。

當然,您可以隨時爲名稱空間URI聲明一個命名常量。