java xml映射对象集合,将XML实体映射到Java对象

I am quite sure, this is one of the many duplicated questions around XML to Java Object conversions.

But I started this thread since I couldn't find simpler or looking for simpler solution.

I have an xsd [Infact I am designing it] and xml.

I would like to auto-map the xml data to Java beans as per mapping

1

A

A

1

Preactivation

Preactivation

1

Now my Java classes will be

public class SummaryCart{

private List summaryElementList;

}

public class SummaryElement {

private int order;

private String id;

private String displayName;

private String property;

private List subElements;

private int maxlines;

private String type;

}

Is there any simple tool/framework which can auto-map the data from XML to Java beans [MUST support attributes/element mapping]. Tutorial will be good.

Btw, I am using Spring framework, if spring-oxm advantage is taken, its welcome.

解决方案

Below is how you could map your object to XML using JAXB (JSR-222). An implementation is included in the JDK/JRE starting with Java SE 6. JAXB is supported by Spring (see section 8.5: http://static.springsource.org/spring-ws/site/reference/html/oxm.html)

SummaryCart

import java.util.List;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="SummaryCart", namespace="SummaryCart")

@XmlAccessorType(XmlAccessType.FIELD)

public class SummaryCart{

@XmlElement(name="SummaryElement")

private List summaryElementList;

}

SummaryElement

import java.util.List;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)

public class SummaryElement {

private int order;

private String id;

private String displayName;

private String property;

private List subElements;

private int maxlines;

@XmlAttribute

private String type;

}

Demo

import java.io.File;

import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {

JAXBContext jc = JAXBContext.newInstance(SummaryCart.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();

File xml = new File("src/forum15881876/input.xml");

SummaryCart sc = (SummaryCart) unmarshaller.unmarshal(xml);

Marshaller marshaller = jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "SummaryCart.xsd");

marshaller.marshal(sc, System.out);

}

}

input.xml/Output

1

A

A

1

Preactivation

Preactivation

0

1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值