JAXB编组Java以输出XML文件 [英] JAXB marshalling Java to output XML file

查看:75
本文介绍了JAXB编组Java以输出XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

problem is how do i generate XML file output instead of 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
        }
    }

}


推荐答案

您已经在编组 nosferatu.xml 。只需删除或评论该行:

You are already marshalling to nosferatu.xml. Just remove or comment the line:

marshaller.marshal(quickXML, System.out);

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

if you don't wish to display the output and close the OutputStream:

os.close();

这篇关于JAXB编组Java以输出XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆