【问题标题】:Reducing code redundancy while creating XML with XOM在使用 XOM 创建 XML 时减少代码冗余
【发布时间】: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


    【解决方案1】:

    不,没有办法摆脱这种冗余,这是一个深思熟虑的决定。在 XOM 中,命名空间是元素本身的基本部分,而不是它在文档中的位置的函数。

    当然,您总是可以为命名空间 URI 声明一个命名常量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      相关资源
      最近更新 更多