Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用XOM创建XML时减少代码冗余_Java_Xml_Xml Serialization_Xom - Fatal编程技术网

Java 使用XOM创建XML时减少代码冗余

Java 使用XOM创建XML时减少代码冗余,java,xml,xml-serialization,xom,Java,Xml,Xml Serialization,Xom,我使用XOM作为我的XML解析库。我也用它来创建XML。下面是用示例描述的场景 场景: 代码: 生成的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:en

我使用XOM作为我的XML解析库。我也用它来创建XML。下面是用示例描述的场景

场景:

代码:

生成的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>
要做到这一点,我只需要以下代码

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
两次。在我的例子中,有数百个名称空间。所以会有太多的再丰富。有没有办法消除这种冗余?

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

当然,您可以始终为名称空间URI声明一个命名常量

<?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");
... ... ...