我使用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;
}
}
答案 0 :(得分:1)
看一下这篇文章:http://blog.bdoughan.com/2010/09/jaxb-xml-infoset-preservation.html
这不完全是你需要的,但可能是更好的方法。
答案 1 :(得分:-1)
Cat cat = new Cat();
cat.setName( "Toby" );
JAXBContext context = JAXBContext.newInstance( Cat.class );
Marshaller m = context.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.setProperty( Marshaller.JAXB_FRAGMENT, Boolean.FALSE );
m.marshal( cat, System.out );
Writer w = null;
try
{
w = new FileWriter( "Cat.xml" );
w.append( "<!-- My awesome comment -->" );
w.flush();
m.marshal( cat, w );
}
finally
{
try
{
w.close();
}
catch ( Exception e )
{
}
}