2013-10-16 29 views
2

我正在使用xstream API如下所示,但現在請指教我可以實現xml到Java對象轉換過程使用API​​以外的其他API的Java相同的東西本身就像JAXB。請adivse如果可能的話那我怎麼可以轉換這個以外使用的XStream ..XML到對象轉換過程以外的其他xstream

假設我們有一個要求,從XML文件加載配置:

01 <config> 
02  <inputFile>/Users/tomek/work/mystuff/input.csv</inputFile> 
03  <truststoreFile>/Users/tomek/work/mystuff/truststore.ts</truststoreFile> 
04  <keystoreFile>/Users/tomek/work/mystuff/CN-user.jks</keystoreFile> 
05 
06  <!-- ssl stores passwords--> 
07  <truststorePassword>password</truststorePassword> 
08  <keystorePassword>password</keystorePassword> 
09 
10  <!-- user credentials --> 
11  <user>user</user> 
12  <password>secret</password> 
13 </config> 

而且我們希望將其加載到配置對象:

01 public class Configuration { 
02 
03  private String inputFile; 
04  private String user; 
05  private String password; 
06 
07  private String truststoreFile; 
08  private String keystoreFile; 
09  private String keystorePassword; 
10  private String truststorePassword; 
11 
12  // getters, setters, etc. 
13 } 

所以基本上我們要做的是:

1 FileReader fileReader = new FileReader("config.xml"); // load our xml file 
2  XStream xstream = new XStream();  // init XStream 
3  // define root alias so XStream knows which element and which class are equivalent 
4  xstream.alias("config", Configuration.class); 
5  Configuration loadedConfig = (Configuration) xstream.fromXML(fileReader); 

回答

0

傑克遜對此很好。在最基本的,你可以簡單地這樣做:

XmlMapper mapper = new XmlMapper(); 
mapper.writeValue(myFile, myObject) 
+0

由於可以請你將我上面的例子中與傑克遜這將幫助我掌握..! –

2

下面是如何將其與JAXB (JSR-222)完成。 JAXB的實現包含在Java SE 6及更高版本中。

Java模型(Configuration

JAXB並不需要任何註釋(參見:http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html),但映射根元素與@XmlRootElement確實讓事情變得更容易。默認情況下,JAXB將從公共屬性派生出映射,但我已使用@XmlAccessorType(XmlAccessType.FIELD),所以我可以排除它們,以便發佈較小的工作類(請參閱:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。

import javax.xml.bind.annotation.*; 

@XmlRootElement(name="config") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Configuration { 

     private String inputFile; 
     private String user; 
     private String password; 

     private String truststoreFile; 
     private String keystoreFile; 
     private String keystorePassword; 
     private String truststorePassword; 

     // getters, setters, etc. 
} 

演示代碼(Demo

下面演示代碼將隱蔽的XML到對象形式,然後將其寫回到XML。

import java.io.File; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Configuration.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     File xml = new File("src/forum19407064/input.xml"); 
     Configuration configuration = (Configuration) unmarshaller.unmarshal(xml); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(configuration, System.out); 
    } 

} 

附加信息

既然你熟悉的XStream這裏是一篇文章我寫了一份與雙方JAXB和XStream的對象模型,看看差別是什麼。