您可以利用 JAXB 和 StAX 并执行以下操作:
演示
如果您想要文档开头的注释,您可以在使用 JAXB 编组对象之前将它们写到目标中。您需要确保将该Marshaller.JAXB_FRAGMENT
属性设置为 true 以防止 JAXB 编写 XML 声明。
import javax.xml.bind.*;
import javax.xml.stream.*;
public class Demo {
public static void main(String[] args) throws Exception {
XMLOutputFactory xof = XMLOutputFactory.newFactory();
XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);
xsw.writeStartDocument();
xsw.writeComment("Author date");
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Foo foo = new Foo();
foo.setBar("Hello World");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(foo, xsw);
xsw.close();
}
}
领域模型(Foo)
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
输出
<?xml version="1.0" ?><!--Author date--><foo><bar>Hello World</bar></foo>
更新
使用 StAX 方法,输出不会被格式化。如果您想格式化以下内容可能更适合您:
import java.io.OutputStreamWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
OutputStreamWriter writer = new OutputStreamWriter(System.out, "UTF-8");
writer.write("<?xml version=\"1.0\" ?>\n");
writer.write("<!--Author date-->\n");
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Foo foo = new Foo();
foo.setBar("Hello World");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(foo, writer);
writer.close();
}
}