Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6533695
  • 博文数量: 915
  • 博客积分: 17977
  • 博客等级: 上将
  • 技术积分: 8846
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-26 09:59
个人简介

一个好老好老的老程序员了。

文章分类

全部博文(915)

文章存档

2022年(9)

2021年(13)

2020年(10)

2019年(40)

2018年(88)

2017年(130)

2015年(5)

2014年(12)

2013年(41)

2012年(36)

2011年(272)

2010年(1)

2009年(53)

2008年(65)

2007年(47)

2006年(81)

2005年(12)

分类: Java

2013-05-13 22:29:18

有多个同名标签时怎么解析

方式一用加注解的方式

xml文件中,有多个元素response,a,b,c,d,name

5个name 中国,美国,俄罗斯,英国,法国

 

1)bean.java

2)在list上加注解

  @XStreamImplicit(itemFieldName="searchContent")// @XStreamImplicit加注解,itemFieldName说明隐含的元素名

3)在test.java中,在根节点转换之前调用

stream.autodetectAnnotations(true);

 

 

package bean;

public class Testresponse {
 
 private User user;

 public User getUser() {
  return user;
 }

 public void setUser(User user) {
  this.user = user;
 }
}

 

package bean;

import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamImplicit;


public class User {
 @XStreamImplicit(itemFieldName="name")//标注加在list上
private List name;

public List getName() {
 return name;
}

public void setName(List name) {
 this.name = name;
}

}

 

package bean;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Set;
import com.thoughtworks.xstream.XStream;

public class Test {
 @SuppressWarnings("unchecked")
 public static void main(String args[]) {
  Reader reader = null;
  File file = new File(
    "C://Users//ThinkPad//workspace8//xstreamtest//WebRoot//a.xml");
  try {
   reader = new FileReader(file);

   XStream xstream = new XStream();

   HashMap hashmap = new HashMap();
   hashmap.put("user", User.class);
   hashmap.put("reponse", Testresponse.class);

   Set keyset = hashmap.keySet();
   for (String str : keyset) {
    xstream.alias(str, hashmap.get(str));
   }

   xstream.autodetectAnnotations(true);
   Testresponse response = (Testresponse) xstream.fromXML(reader);
   System.out.println(response);
   String s = xstream.toXML(response);
   System.out.println(s);

  } catch (Exception e) {
   e.printStackTrace();
  }

 }
}

 

 



  
   jack1
   jack2
   jack3
  

阅读(5220) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~