您知道有没有JAXB设置可防止在生成的XML中出现standalone="yes"吗?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
您知道有没有JAXB设置可防止在生成的XML中出现standalone="yes"吗?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
JAXB是JDK1.6的一部分。
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
你可以使用
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
或者marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", 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中的standalone="yes"
属性去除,以避免它成为生成的XML的一部分。
这个属性:
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);
...可以用来实现无:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
然而,我不认为这是最佳实践。
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
如果您仅使用默认的javax.xml包,则可以将marshaller的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();
我正在使用Java 1.8和JAXB 2.3.1
首先,确保在pom.xml中使用的是Java 1.8版本。
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
然后在源代码中,我使用了以下内容:(关键是内部部分)
// remove standalone=yes
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
只是尝试
private String marshaling2(Object object) throws JAXBException, XMLStreamException {
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
StringWriter writer = new StringWriter();
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
jaxbMarshaller.marshal(object, writer);
return writer.toString();
}