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
兩次。在我的情況下,有數百個命名空間。所以會有太多的兌換。有什麼辦法擺脫這種冗餘?