0

我正在使用 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;
    }

}
4

2 回答 2

1

看看这篇文章:http ://blog.bdoughan.com/2010/09/jaxb-xml-infoset-preservation.html

这不完全是您所需要的,但可能是更好的方法。

于 2012-05-07T18:25:26.693 回答
-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 )
  {
  }
}
于 2012-05-07T17:59:37.923 回答