我有一个类,应该解析一个XML文件,就像这样:
<customers>
...
<customer>
<id>123456</id>
<name>Mike</name>
<orders>
...
<order>
<id>233658</id>
<positions>
...
<position>
<id>12345</id>
<price>10.0</price>
<count>5</count>
</position>
...
</positions>
</order>
...
</orders>
</customer>
<customers>
我将使用JAXB对其进行反序列化,然后处理结果对象以获取统计信息(如最大订单金额、总订单金额等)。
在这种情况下使用3级foreach循环是一种不好的做法吗?
public void getStatistics() {
for (Customer customer: this.customers.getCustomer()) {
BigDecimal customerTotalAmount = new BigDecimal(0);
for (Order order : customer.getOrders().getOrder()) {
BigDecimal orderAmount = new BigDecimal(0);
for (Position position : order.getPositions().getPosition()) {
orderAmount = orderAmount.add( position.getPrice().multiply(new BigDecimal(position.getCount())) );
}
customerTotalAmount = customerTotalAmount.add(orderAmount);
this.totalOrders++;
}
this.totalAmount = this.totalAmount.add(customerTotalAmount);
}
}
客户(Customer)、订单(Order)和职位(Position)类已从XSD模式自动生成,我认为修改它们不好。
我做错了什么?如何避免这些嵌套循环?
谢谢。