2014-10-01 19 views
6

嗨,通過以下鏈接我能夠將JAXB轉換爲java對象並使用下面的語句在控制檯中打印它。如何將jaxb打印到java對象到記錄器中

http://www.mkyong.com/java/jaxb-hello-world-example/

jaxbMarshaller.marshal(customer, System.out); 

,但我想打印記錄儀的輸出。

前)log.info(客戶)或log.debug(客戶)

我使用Apache log4j.Does人有任何想法?

+3

寫入到一個'StringWriter'和日誌'stringWriter.toString()'。 – lexicore 2014-10-01 11:12:46

回答

4

下面一個可行的辦法..

Customer customer = new Customer(); 
//set customer attributes 
JAXBContext jc = JAXBContext.newInstance(Customer.class); 
Marshaller marshaller = jc.createMarshaller(); 
StringWriter stringWriter = new StringWriter(); 
marshaller.marshal(customer, stringWriter); 
log.info(stringWriter.toString()); 
+0

謝謝。它工作的很好。在stringWriter中有任何漂亮的打印選項,因爲rightNow它打印在一條水平線上。 – VelNaga 2014-10-01 13:21:54

+3

你應該添加這行來格式化輸出'marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);' – Xstian 2014-10-01 13:24:50

+0

你真棒。謝謝。 – VelNaga 2014-10-01 13:39:15