我有一个自定义方法,它读取XML文件并创建许多对象。
方法代码:
public static Property[] initProperties() {
Property p1, p2;
XStream xstream = new XStream();
xstream.alias("Property", Property.class);
xstream.registerConverter(new PropsConverter());
try {
ObjectInputStream in = xstream.createObjectInputStream(Utils.class.getResourceAsStream("Properties.xml"));
p1 = (Property) in.readObject();
System.out.println("P1_"+p1.getName());
p2 = (Property) in.readObject();
System.out.println("P2_"+p2.getName());
Property[] array = {p1,p2};
return array;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
自定义转换器在每一步都内置了System.Out.Println
,因此我可以看到转换器是否正确读取内容。它做了。我有这个XML文件
<root>
<Property>
<name>Property 1</name>
<ownedBy>NULL</ownedBy>
<price>1000</price>
</Property>
<Property>
<name>Test2</name>
<ownedBy>NULL</ownedBy>
<price>1000</price>
</Property>
</root>
转换器向右吐出两个。当我在另一个类中调用initProperties()
函数来填充新数组时,我遇到了一个问题。
主类
try {
Properties[] availableProperties = Utils.initProperties();
} catch (Exception e) {
e.printStackTrace();
}
现在除非我完全弄错了System.out.println(availableProperties[0].getName());
,否则应打印属性1,而System.out.println(availableProperties[1].getName());
应打印测试2。
但我得到两行:
测试2 测试2
为什么?
自定义转换器
public class PropsConverter实现了Converter {
public boolean canConvert(Class clazz) {
return clazz.equals(Property.class);
}
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Property props = (Property) value;
writer.startNode("name");
writer.setValue(props.getName());
writer.endNode();
writer.startNode("ownedBy");
writer.setValue(props.getName());
writer.endNode();
writer.startNode("price");
writer.setValue(props.getPriceAsString());
writer.endNode();
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Property props = new Property();
reader.moveDown();
props.setName(reader.getValue());
// System.out.println("NAME_" + reader.getValue());
reader.moveUp();
reader.moveDown();
props.setOwnedBy(reader.getValue());
// System.out.println("OWNEDBY_" + reader.getValue());
reader.moveUp();
reader.moveDown();
props.setPrice(Float.parseFloat(reader.getValue()));
// System.out.println("PRICE_" + reader.getValue());
reader.moveUp();
return props;
}
}