我正在尝试使用XStream将类实例转换为XML。一切都很好,除了一件事,我希望有人可以帮我解决。
作为前提,我有许多“嵌套”类(按顺序,OrderStatusImport
- > OrderCollection
- > Order
- > OrderLine
),但焦点由班级Order
表示;如上所述,它的每个实例都包含OrderLine
个对象的列表。就像这样:
public class Order {
//attribute's declarations...
ArrayList<OrderLine> orderLines;
}
这是我的格式化程序类,我在其中调用主XStream逻辑:
private String createImportXml(OrderStatusImport orderStatusImport) {
Object xstream = null;
if (xstream == null) {
xstream = new XStream() {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new UpperCaseMapper(next);
}
};
}
((XStream) xstream).alias("OrderStatusImport", OrderStatusImport.class);
((XStream) xstream).alias("OrderCollection", OrderCollection.class);
((XStream) xstream).alias("Order", Order.class);
((XStream) xstream).alias("OrderLine", OrderLine.class);
((XStream) xstream).omitField(Order.class, "OrderLines");
String decl = "\n";
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String xml = "";
xml += ((XStream) xstream).toXML(orderStatusImport);
return (header + decl + xml + decl);
}
问题是生成的XML具有不需要的标记OrderLines。 它表示为:
<Order>
<OrderItemsTotal>266.00</OrderItemsTotal>
<OrderShipping>0.00</OrderShipping>
<OrderCodFee>0.00</OrderCodFee>
<OrderTotal>266.00</OrderTotal>
<OrderStatus>H4</OrderStatus>
<OrderLines>
<OrderLine>
<ItemNumber>000001</ItemNumber>
<DCNumber>DC10</DCNumber>
<StorageLocation>1001</StorageLocation>
<OrderLineStatus>C0</OrderLineStatus>
<CancelReasonCode></CancelReasonCode>
<Quantity>1</Quantity>
<ItemTotal>167.00</ItemTotal>
</OrderLine>
<OrderLine>
<ItemNumber>000002</ItemNumber>
<DCNumber>DC10</DCNumber>
<StorageLocation>1001</StorageLocation>
<OrderLineStatus>C0</OrderLineStatus>
<CancelReasonCode></CancelReasonCode>
<Quantity>1</Quantity>
<ItemTotal>99.00</ItemTotal>
</OrderLine>
</OrderLines>
</Order>
,虽然我想要这个(没有OrderLines标签):
<Order>
<OrderItemsTotal>266.00</OrderItemsTotal>
<OrderShipping>0.00</OrderShipping>
<OrderCodFee>0.00</OrderCodFee>
<OrderTotal>266.00</OrderTotal>
<OrderStatus>H4</OrderStatus>
<OrderLine>
<ItemNumber>000001</ItemNumber>
<DCNumber>DC10</DCNumber>
<StorageLocation>1001</StorageLocation>
<OrderLineStatus>C0</OrderLineStatus>
<CancelReasonCode></CancelReasonCode>
<Quantity>1</Quantity>
<ItemTotal>167.00</ItemTotal>
</OrderLine>
<OrderLine>
<ItemNumber>000002</ItemNumber>
<DCNumber>DC10</DCNumber>
<StorageLocation>1001</StorageLocation>
<OrderLineStatus>C0</OrderLineStatus>
<CancelReasonCode></CancelReasonCode>
<Quantity>1</Quantity>
<ItemTotal>99.00</ItemTotal>
</OrderLine>
</Order>
我使用omitField()
而不是@XStreamOmitField
注释尝试过,但也许我误解了这些(我是XStream中的新手)。
在你提到之前,我也可以在生成的String上使用简单的replace()
,但我不知道如何以这种方式保留缩进。
答案 0 :(得分:5)
您想要的是隐式收集。您可以通过两种方式定义它
使用注释
public class Order {
@XStreamImplicit(itemFieldName="OrderLine")
ArrayList<OrderLine> orderLines;
}
或使用代码
xstream.addImplicitCollection(Order.class, "orderLines", "OrderLine", OrderLine.class);