Ket*_*Ket 13 java xml jaxb marshalling
问题是如何生成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
}
}
}
Run Code Online (Sandbox Code Playgroud)
bdo*_*han 11
如果您使用的是JAXB 2.1或更高版本,则可以直接编组java.io.File对象:
File file = new File( "nosferatu.xml" );
marshaller.marshal( quickXML, file );
Run Code Online (Sandbox Code Playgroud)
相应的Javadoc
你已经在编组了nosferatu.xml.只需删除或评论该行:
marshaller.marshal(quickXML, System.out);
Run Code Online (Sandbox Code Playgroud)
如果您不想显示输出并关闭OutputStream:
os.close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64958 次 |
| 最近记录: |