我正在使用 JAXB 编组对象,并且当前我的控制台输出与我生成的 XML 文件不同:
安慰:
<!-- My awesome comment -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Cat>
<name>Toby</name>
</Cat>
生成:
<Cat>
<name>Toby</name>
</Cat>
我希望控制台中的输出与其中生成的内容相匹配,Cat.xml
但事实并非如此。我的问题是我生成“正确”的方法有什么不正确的Cat.xml
?最低功能程序如下:
public class CatDriver{
public static void main(String[] args) throws JAXBException, IOException,
ParserConfigurationException, TransformerException {
Cat cat = new Cat();
cat.setName("Toby");
JAXBContext context = JAXBContext.newInstance(Cat.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.setProperty(
"com.sun.xml.bind.xmlHeaders",
"<!-- My awesome comment"
+ " --> \n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
m.marshal(cat, System.out);
Writer w = null;
try {
w = new FileWriter("C:/test/Cat.xml");
m.marshal(cat, w);
} finally {
try {
w.close();
} catch (Exception e) {
}
}
}
}
@XmlRootElement(name = "Cat")
class Cat {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}