您是否知道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