我正在使用如下所示的 xstream api,但现在请告知我是否可以使用 API 实现相同的 xml 到 java 对象转换过程,而不是像 JAXB 这样的 java 本身中的 xstream。如果可能的话,请注意,除了使用 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);