如何使用XStream将对象列表转换为XML文档

如何使用XStream将对象列表转换为XML文档?

以及如何将其反序列化?

这是我的xml

   Guilherme 10 
address,address,address,address,
Guilherme 10
address,address,address,address,

Person bean包含3个字段如何使用自定义转换器将其转换回Bean List?

您不一定需要CustomConverter。

您需要一个class级来保存您的列表:

 public class PersonList { private List list; public PersonList(){ list = new ArrayList(); } public void add(Person p){ list.add(p); } } 

要将列表序列化为XML:

  XStream xstream = new XStream(); xstream.alias("person", Person.class); xstream.alias("persons", PersonList.class); xstream.addImplicitCollection(PersonList.class, "list"); PersonList list = new PersonList(); list.add(new Person("ABC",12,"address")); list.add(new Person("XYZ",20,"address2")); String xml = xstream.toXML(list); 

要将xml反序列化为人员对象列表:

  String xml = "..."; PersonList pList = (PersonList)xstream.fromXML(xml); 

只需使用std toXml和fromXml方法,请参阅http://en.wikipedia.org/wiki/XStream以获取示例。 另请参阅http://x-stream.github.io/converters.html ,了解默认转换的工作原理。

好的,所以默认的转换器在你的情况下不会很好用。 你需要遵循:

http://x-stream.github.io/converter-tutorial.html

加载XML

 public static Object Load(String xmlPath) throws Exception { File FileIn = new File(xmlPath); if(FileIn.exists()) { //Initialise Doc DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document Doc = builder.parse(FileIn); //Initialise XPath XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); String objectClassLocation = xpath.evaluate("/object/@class",Doc); Object ObjType; //Create List of attributes for the Student XPathExpression xpathExpression = xpath.compile("/object/*"); NodeList ObjTypeAttributes = (NodeList)xpathExpression.evaluate(Doc, XPathConstants.NODESET); ObjType = CreateObject(ObjTypeAttributes, objectClassLocation); return ObjType; } return null; } 

创建对象

 public static Object CreateObject(NodeList ObjectAttributes, String Location) throws Exception { Class ClassName = Class.forName(Location); Object object = ClassName.newInstance(); Field[] fields = ClassName.getFields(); for(int x = 0; x < fields.length;x++) { for(int y = 0; y 

创建列表(仅在xml具有对象对象时使用)

 public static ArrayList CreateList(NodeList ArrayNodeList) throws Exception { ArrayList List = new ArrayList(); for(int x = 0; x < ArrayNodeList.getLength();x++) { if(!(ArrayNodeList.item(x) instanceof Text)) { Node curNode = ArrayNodeList.item(x); NodeList att = curNode.getChildNodes(); String Location = ArrayNodeList.item(x).getAttributes().item(0).getNodeValue(); Object newOne = CreateObject(att, Location); List.add(newOne); } } return List; } 

我使用的XML示例