我想序列化一个对象层次结构,包括从基类“事物”派生的对象列表。这很好用,包括反序列化 - 但 XML-Simple 坚持编写一个属性来指定实际使用的 Java 类
当我用下面的java代码创建一个xml文件时,内容是这样的:
<example1>
<things>
<fruit class="com.mumpitz.simplexmltest.Apple" id="17">
<sugar>212</sugar>
</fruit>
<fruit class="com.mumpitz.simplexmltest.Orange" id="25" weight="11.2"/>
</things>
</example1>
但这不是我想要的。我想拥有
<example1>
<things>
<apple id="17">
<sugar>212</sugar>
</apple>
<orange id="25" weight="11.2"/>
</things>
</example1>
没有类属性的“apple”和“orange”元素,而不是具有此类属性的“fruit”。这可能吗?
(第二个 xml 符合现有架构;添加额外属性不是一种选择)
这是代码:
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
class Fruit {
@Attribute(name = "id")
protected final int id;
Fruit(
@Attribute(name = "id")
int id) {
this.id = id;
}
int getObjectId() {
return id;
}
}
@Root
class Apple extends Fruit {
private final int sugar;
@Element(type = Fruit.class)
public Apple(
@Attribute(name = "id")
int id,
@Element(name = "sugar")
int sugar) {
super(id);
this.sugar = sugar;
}
@Element(name = "sugar")
public int getSugar() {
return this.sugar;
}
@Override
public String toString() {
return "id: " + id + ", sugar: " + sugar;
}
}
@Root
class Orange extends Fruit {
@Attribute
public double weight;
public Orange(
@Attribute(name = "id")
int id) {
super(id);
}
@Override
public String toString() {
return "id: " + id + ", weight: " + weight;
}
}
@Root
public class Example1 {
@ElementList
public ArrayList<Fruit> things = new ArrayList<Fruit>();
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("things:\n");
for (int i=0; i<things.size(); i++) {
sb.append(" " + things.get(i).toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
static Example1 createDummy() {
Example1 d = new Example1();
d.things.add(new Apple(17, 212));
Orange or = new Orange(25);
or.weight = 11.2;
d.things.add(or);
return d;
}
static String msg;
static Example1 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static public boolean write(String path) {
Serializer serializer = new Persister();
Example1 example = Example1.createDummy();
File result = new File(path);
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example1.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}