我有一个需要编组为 XML 的对象。为此,我正在使用 JAXB。创建了生成的 XML 文件,但是我最终得到了重复的节点:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order>
<supplier_id>suppliername</supplier_id>
<store_name>storename</store_name>
<order_id>1234567890</order_id>
<order_item>
<order_item_id>0987654321</order_item_id>
<item_state>Shipped</item_state>
<item_state_date>2012-12-27T14:40:00.000-05:00</item_state_date>
<carrier_code>NA</carrier_code>
<carrier_name>CarrierName</carrier_name>
<shipping_method>Expedited</shipping_method>
<tracking_number>348134987124872734817324</tracking_number>
<backorder_replacement_sku_price>0.0</backorder_replacement_sku_price>
</order_item>
<order_item>
<order_item_id>0987654321</order_item_id>
<item_state>Shipped</item_state>
<item_state_date>2012-12-27T14:40:00.000-05:00</item_state_date>
<carrier_code>NA</carrier_code>
<carrier_name>CarrierName</carrier_name>
<shipping_method>Expedited</shipping_method>
<tracking_number>348134987124872734817324</tracking_number>
<backorder_replacement_sku_price>0.0</backorder_replacement_sku_price>
</order_item>
....
我只需要第一个<order_item>
节点,随后的节点错误地存在。
我的代码如下:
JAXBContext context = JAXBContext.newInstance(classname.class.getPackage().getName());
Marshaller marsheller = context.createMarshaller();
Order order = new Order();
OrderItem orderItem = new OrderItem();
...Business logic related to our ERP system...
//We start a loop here to iterate over search results. The goal is to have one XML file per search row returned. No knowledge of the ERP system is required.
for (SearchRow row : results.getSearchRowList().getSearchRow()) {
//we capture our variables from the search results here and build our order and orderItem objects with them.
order.setSupplierId("suppliername");
order.setStoreName("storename");
order.setOrderId(orderNumber);
orderItem.setOrderItemId(orderItemId);
orderItem.setItemState(StatusCodeType.SHIPPED);
orderItem.setItemStateDate(date2);
orderItem.setCarrierCode("NA");
orderItem.setCarrierName(carrierName);
orderItem.setShippingMethod(shippingMethod);
orderItem.setTrackingNumber(trackingNumber);
order.getOrderItem().add(orderItem);
File f = new File("tempFiles/" + order.getOrderId() + ".xml");
marsheller.marshal(order, f);
}
我认为问题在于循环,但是如果我在从对象本身创建对象后记录所有变量,则只会显示 orderItem 结果而不是多个 orderItems。
谁能指出我偏离轨道的方向?