1.Dependcy
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.9</version>
</dependency>
2.定义XMLMapper
private static final XmlMapper xmlMapper;
static {
xmlMapper = new XmlMapper();
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
3. 构建实体类
根据想要XML数据中获取的数据来定义字段,@JacksonXmlRootElement注解是定义最外层节点,
@JacksonXmlProperty获取下一个节点数据.
@Data
@JacksonXmlRootElement(localName = "request")
public class DeliveryOrderCreateRequest {
private DeliveryOrder deliveryOrder;
@JacksonXmlElementWrapper(localName = "orderLines")
@JacksonXmlProperty(localName="orderLine")
private List<CreateOrderLine> orderLines;
}
4.将XML数据转化为定义实体类
DeliveryOrderCreateRequest requestData = xmlMapper.readValue(xmlData, DeliveryOrderCreateRequest.class);
5.根据上述,数据转换为如下列
deliveryOrder自由定义下一级实体类
<request>
<deliveryOrder>
<arAmount>0</arAmount>
<createTime>2022-09-22 17:46:35</createTime>
<senderInfo>
<area></area>
<city>北京市</city>
<company></company>
<detailAddress>光谷大道</detailAddress>
</senderInfo>
<shopNick>eplus001</shopNick>
<sourcePlatformCode>TB</sourcePlatformCode>
<totalAmount>123.000000</totalAmount>
<warehouseCode>ULHKG</warehouseCode>
</deliveryOrder>
<orderLines>
<orderLine>
<actualPrice>123.000000</actualPrice>
<discountAmount>123.000000</discountAmount>
<inventoryType>ZP</inventoryType>
<itemCode>PN001</itemCode>
</orderLine>
</orderLines>
</request>
转换为:
eliveryOrderCreateRequest(deliveryOrder=DeliveryOrder( warehouseCode=ULHKG, sourcePlatformCode=TB,createTime=2022-09-22 17:46:35, shopNick=eplus001, totalAmount=123.0, senderInfo=SenderInfo(city=北京市, area=,detailAddress=光谷大道),orderLines=[CreateOrderLine(inventoryType=ZP, itemCode=PN001, discountAmount=123.00,actualPrice=123.00)])