因为在Java核心库不支持arraylist xml直接注解,这里可以自己写个小工具类
Contact.java:
package com.newer.xml; import java.util.ArrayList; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; // 根节点 @Root(name = "person") public class Contact { @Attribute int id; @Element String name; @ElementList(inline = true, entry = "phone", required = false) ArrayList<String> phoneList = new ArrayList<>(); public Contact() { } public Contact(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Contact [id=" + id + ", name=" + name + ", phoneList=" + phoneList + "]"; } }
工具列ContactList.java:
package com.newer.xml; import java.util.ArrayList; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; // 注解 @Root(name = "contact-list") public class ContactList { // 委托 @ElementList(inline = true) ArrayList<Contact> contacts = new ArrayList<>(); public void add(Contact c) { contacts.add(c); } public Contact get(int i) { return contacts.get(i); } }
运行的开始Demo.java:
注意required属性设置false说明当前属性是可空的
这里先写如,然后注释,再读取,当然可以仿照案例直接写在控制台方便查看效果:
package com.newer.xml; import java.io.File; import java.util.ArrayList; import org.simpleframework.xml.core.Persister; public class Demo { public static void main(String[] args) { Persister pr = new Persister(); try { ContactList list = pr.read(ContactList.class, new File("c.xml")); for (Contact c : list.contacts) { System.out.println(c); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Contact c1 = new Contact(1, "alice"); // c1.phoneList.add("131"); // c1.phoneList.add("139"); // // Contact c2 = new Contact(2, "bob"); // Contact c3 = new Contact(3, "jack"); // c3.phoneList.add("1"); // c3.phoneList.add("2"); // c3.phoneList.add("3"); // c3.phoneList.add("4"); // // ContactList list = new ContactList(); // list.add(c1); // list.add(c2); // list.add(c3); // // // Persister pw = new Persister(); // // try { // pw.write(list, new File("c.xml")); // // } catch (Exception e) { // e.printStackTrace(); // } } }
时间: 2024-10-27 05:45:53