jaxb 使用之 marshall List unmarshall

               

@XmlElementpublic class Post { private long id; //帖子编号 private String tiebaName; //贴吧名称 private String url;  //帖子url private String title; //标题 private String author; //作者 //... setter getter}@XmlRootElement(name="jaxbList")public class PostList {  private List<Post> element = new ArrayList<Post>(); @XmlElement public List<Post> getElement() {  return element; } public void setElement(List<Post> element) {  this.element = element; } }

如果将@XmlElement注解应用到element字段上面,则会报异常, 搞不懂 , 先放一下

 

 

 

 

 PostList postList = new PostList();  postList.getElement().add(post);  postList.getElement().add(post2);  marshallList(postList, path + "posts111.xml", path+"posts.xsd");

 

PostList pl = unmarshallList(PostList.class, path + "posts111.xml", path+"posts.xsd");  for(Post p : pl.getElement()){   System.out.println(p.getAuthor());   System.out.println(p.getId());  }

 

marshall   unmarshall 相关代码

 

public static <T> void marshallList(PostList jaxbList,String xmlPath,String xsdPath)throws Exception{  JAXBContext context = JAXBContext.newInstance(jaxbList.getClass());  Marshaller ms = context.createMarshaller();  if(xsdPath != null){   try {    File xsdFile = new File(xsdPath);    Schema schema =  SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)    .newSchema(xsdFile);    ms.setSchema(schema);   } catch (Exception e) {    e.printStackTrace();   }  }  ms.marshal(jaxbList, new File(xmlPath)); } public static <T> PostList unmarshallList(Class<PostList> clazz,String xmlPath,String xsdPath) throws Exception{  JAXBContext context = JAXBContext.newInstance(clazz);  Unmarshaller ums = context.createUnmarshaller();  if(xsdPath != null){   try {    File xsdFile = new File(xsdPath);    Schema schema =  SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)    .newSchema(xsdFile);    ums.setSchema(schema);   } catch (Exception e) {    e.printStackTrace();   }  }  PostList jaxbList = (PostList) ums.unmarshal(new File(xmlPath));  return jaxbList; }

 

           
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值