1. 程式人生 > >xstream 小結 一個標籤下有多個同名標籤

xstream 小結 一個標籤下有多個同名標籤

有多個同名標籤時怎麼解析

方式一用加註解的方式

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<String> name;

public List<String> getName() {
 return name;
}

public void setName(List<String> 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<String, Class> hashmap = new HashMap<String, Class>();
   hashmap.put("user", User.class);
   hashmap.put("reponse", Testresponse.class);

   Set<String> 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();
  }

 }
}

<?xml version="1.0" encoding="UTF-8"?>
<reponse>
  <user>
   <name>jack1</name>
   <name>jack2</name>
   <name>jack3</name>
  </user>
</reponse>