JAXB 编组 Java 以输出 XML 文件

2022-09-03 00:55:29

问题是我如何生成XML文件输出而不是system.out?

package jaxbintroduction;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        itemorder.Book quickXML = new itemorder.Book();

        quickXML.setAuthor("Sillyme");
        quickXML.setDescription("Dummie book");
        quickXML.setISBN(123456789);
        quickXML.setPrice((float)12.6);
        quickXML.setPublisher("Progress");
        quickXML.setTitle("Hello World JAVA");

        try {            
            javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(quickXML.getClass().getPackage().getName());
            javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(quickXML, System.out);
            OutputStream os = new FileOutputStream( "nosferatu.xml" );
            marshaller.marshal( quickXML, os );

        } catch (javax.xml.bind.JAXBException ex) {
            // XXXTODO Handle exception
            java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
        }
    }

}

答案 1

如果您使用的是 JAXB 2.1 或更高版本,那么可以直接封送至对象:java.io.File

 File file = new File( "nosferatu.xml" );
 marshaller.marshal( quickXML, file );

Corrsponding Javadoc


答案 2

您已经在编组到 .只需删除或注释该行:nosferatu.xml

marshaller.marshal(quickXML, System.out);

如果您不希望显示输出并关闭 :OutputStream

os.close();

推荐