我有一个用于配置一些规则的XML,它没有复杂的结构,但是这个配置在我的系统中的任何地方使用,所以我想将此XML解析为java对象并设计为单例模式,有什么好方法吗?可以用它直接将XML解组为Java对象而无需编写太多代码吗?
我在Google上做了一些研究,知道JAXB是一个选择,我的应用程序只是一些读取规则然后遵循做事的工具程序,JAXB可以更广泛地用于Web服务,它适合我的项目吗?
如果是的话,最重要的问题是,我使用xjc根据xsd文件生成java对象源类,解组后我将直接得到这些configurationType对象,是否有必要再次转换,(从JaxB类到我拥有的java pojo对象配置),我看到大多数编码器都这样做,但为什么呢?因为它们是一些数据,只是从生成的对象到JAXB并复制到我们自己创建的POJO对象
JAXB 是一个理想的解决方案。但您不一定需要 xsd 和 xjc。通常,您没有 xsd,但您知道 xml 是什么。只需分析您的 xml,例如,
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
创建必要的模型类:
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
尝试解组:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));
检查结果,修复错误!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)