[英]XML hierarchy with Java properties
Let's say I have a class Foo with some primitive instance variables. 假设我有一个带有一些原始实例变量的Foo类。 I initialize these with properties in XML files. 我用XML文件中的属性初始化它们。 Now every Foo also has a Bar as a variable, which in turn has its own properties. 现在,每个Foo都有一个Bar作为变量,而Bar又具有自己的属性。 Since these are tied to the enclosing object, it would make sense to keep them in the same file. 由于这些都与封闭对象相关联,因此将它们保留在同一文件中是有意义的。 How should I format the XML so that it can initialize the object as well? 我应该如何格式化XML,以便它也可以初始化对象?
Take a look at XStream , which allows you to trivially serialise/deserialise a Java object hierarchy to/from XML. 看一下XStream ,它使您可以轻松地将Java对象层次结构与XML序列化/反序列化。
At its simplest it'll work with a POJO, which no additional work (no interfaces/base classes etc. required). 最简单的说,它将与POJO一起使用,而POJO不需要其他工作(不需要接口/基类等)。 But you can customise how it serialises and deserialises to rename elements etc. to fit within an existing XML framework. 但是,您可以自定义序列化和反序列化的方式,以重命名元素等以适合现有XML框架。
JAXB is worth a look: JAXB值得一看:
public class JaxbDemo {
@XmlRootElement
public static class Foo {
@XmlElement public Bar bar;
}
public static class Bar {
@XmlAttribute public int baz;
}
public static void main(String[] args) {
String xml = "<foo><bar baz='123'/></foo>";
Foo foo = JAXB.unmarshal(new StringReader(xml), Foo.class);
System.out.println(foo.bar.baz);
}
}
(Public members used for demo purposes.) (用于演示目的的公共成员。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.