【发布时间】:2012-11-28 08:29:42
【问题描述】:
我使用 XOM 作为我的 XML 解析库。我也用它来创建 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 两次。就我而言,有数百个命名空间。所以会有太多的冗余。有没有办法摆脱这种冗余?
【问题讨论】:
标签: java xml xml-serialization xom