我正在使用xstream api,如下所示,但现在请建议我可以在Java本身(如JAXB)中使用除xstream之外的API实现xml到java对象转换过程的相同内容。如果有可能请试着除了使用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>
我们想将其加载到Configuration对象中:
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 :(得分:2)
以下是JAXB (JSR-222)的完成方式。 Java SE 6及更高版本中包含JAXB的实现。
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映射对象模型的文章,以了解它们之间的区别。
答案 1 :(得分:0)
杰克逊非常棒。最基本的,你可以这样做:
XmlMapper mapper = new XmlMapper();
mapper.writeValue(myFile, myObject)