您是否知道JAXB设置可防止在生成的XML中生成standalone =“yes”?JAXB - 从生成的XML中删除'standalone =“yes”'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
您是否知道JAXB设置可防止在生成的XML中生成standalone =“yes”?JAXB - 从生成的XML中删除'standalone =“yes”'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
可用于没有
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
但是我难道不认为这是最好的做法。
如果您使文档依赖于DOCTYPE
(例如,使用命名实体),那么它将停止独立,因此standalone="yes"
将不允许在XML声明中使用。
但是独立XML可以在任何地方使用(对于不加载外部数据的XML解析器而言,非独立式会产生问题)。
我不明白这个声明是如何成为一个问题的,除了与不支持XML的软件的互操作性,还有一些破解的本土XML类巫术。
在JAXB是JDK1.6
的一部分marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
您可以使用
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
或
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE)
禁用默认XML声明,然后添加你的定制XML声明,
<?xml version="1.0" encoding="UTF-8"?>
通过
marshaller.setProperty("com.sun.xml.bind.xmlHeaders",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
于所生成的XML,从而避免了独立= “是”属性。
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
这对JDK1.7有效。 standalone = \“no \”可以被移除以获得xml部分的剩余部分
我没有足够高的“声誉”来拥有“特权”发表评论。 ;-)
@Debasis,请注意,您所指定的属性:
"com.sun.xml.internal.bind.xmlHeaders"
应该是:
"com.sun.xml.bind.xmlHeaders" (without the "internal", which are not meant to be used by the public)
如果我用的是 “内部” 属性像你一样,我得到一个javax.xml.bind。PropertyException
只是当其他人还在这个问题struggeling,您可以考虑使用
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
删除所有的XML声明的,只是写自己的String
你的输出流/方法的开始
如果您仅使用缺省javax.xml包,可以将编组器的JAXB_FRAGMENT选项设置为'true'(这省略了默认的xml处理指令),并使用XMLStreamWriter的writeProcessingInstruction方法插入您自己的:
xmlStreamWriter.writeProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
jaxbMarshaller.marshal(object, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
这是为什么? – Kornel 2008-12-14 18:56:55