2016-05-25 43 views
0

我想將只是xml的輸入字符串轉換爲JAVA對象。我正在使用JAXB。但我的問題來自調用應用程序,我將以字符串的形式接收XML。但jaxbUnmarshaller.unmarshal(inputXML);需要輸入中的FILE對象。那麼是否有一些方法可以將輸入字符串轉換爲FILE對象,而無需手動將此傳入內容寫入磁盤。將輸入字符串轉換爲文件對象

以下是我的方法片段

public void xmlToObject(String inputXML){ 
     try{ 
      JAXBContext jaxbContext = JAXBContext.newInstance(LineItemsBeanList.class); 
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
      LineItemsBeanList objreq= (LineItemsBeanList) jaxbUnmarshaller.unmarshal(inputXML); 
      printLineItems(objreq.getLineItemsBean()); 
      nba.processLineItems(objreq.getLineItemsBean()); 
      nba.printFinalSetOfRules(); 
     } 
     catch(Exception e){ 
      System.out.println(e); 

     } 
    } 

回答

0

你並不需要做一個File對象來解決這個問題。使用javax.xml.transform.stream.StreamSource中

從一個StringBuffer解組:

docs for JAXB Unmarshaller採取

JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); 
Unmarshaller u = jc.createUnmarshaller(); 
StringBuffer xmlStr = new StringBuffer("<?xml version="1.0"?>..."); 
Object o = u.unmarshal(new StreamSource(new StringReader(xmlStr.toString()))); 

在你的情況,你可以使用類似的方法從字符串解組:

LineItemsBeanList objreq = (LineItemsBeanList) jaxbUnmarshaller.unmarshal(
    new StreamSource(new StringReader(inputXML)));