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:
<?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 では、ここでinfo
名前空間がノード自体に追加されていることに注意してください。しかし、これをルート要素に追加する必要があります。以下のように
<?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
2回追加する必要がありました。私の場合、何百もの名前空間があります。したがって、冗長性が非常に高くなります。この冗長性を取り除く方法はありますか?