我使用 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
两次。就我而言,有数百个 namespace 。所以会有太多的冗余。有什么办法可以消除这种冗余吗?
最佳答案
不,没有办法消除这种冗余,这是一个深思熟虑的决定。在 XOM 中, namespace 是元素本身的基本部分,而不是其在文档中的位置的函数。
当然,您始终可以为命名空间 URI 声明一个命名常量。
关于java - 使用 XOM 创建 XML 时减少代码冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13600813/