具体信息参见: http://simple.sourceforge.net/
比如要操作的XML为:
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book catalog="Programming"> <title lang="en">C++ Programming Language</title> <author>Bjarne Stroustrup</author> <year>1998</year> <price>98.0</price> </book> <book catalog="Networking"> <title lang="en">TCP/IP Illustrated</title> <author>Richard Stevens</author> <year>1996</year> <price>56.0</price> </book> </bookstore>
首先建立POJO类:
public class Book { @Attribute String catalog =null; @ElementMap (key="lang" ,entry="title" ,inline=true ,attribute=true) Map<String,String> map = null; @Element String author = null; @Element String year = null; @Element String price = null; public Book(){ //必要的.在读取的时候默认调用无参构造. } //省略set,get }
@Root (name="bookstore") public class Bookstore { @ElementList (inline=true) List<Book> book = null; public List<Book> getBook() { return book; } public void setBook(List<Book> book) { this.book = book; } }
序列化测试:
@Test public void test_toXML(){ //序列化 Serializer serializer = new Persister(); HashMap<String,String> hm = new HashMap<String, String>(); hm.put("en", "C++ Programming Language"); HashMap<String,String> hm1 = new HashMap<String, String>(); hm1.put("en", "TCP/IP Illustrated"); List<Book> book = new ArrayList<Book>(); book.add(new Book(hm,"Bjarne Stroustrup","1998","98.0","Programming")); book.add(new Book(hm1,"Richard Stevens","1996","56.0","Networking")); Bookstore bs = new Bookstore(); bs.setBook(book); OutputStream os = new ByteArrayOutputStream(); try { serializer.write(bs, os); } catch (Exception e) { e.printStackTrace(); } System.out.println(os.toString()); try { os.close(); } catch (IOException e) { e.printStackTrace(); } }
输出:
<bookstore> <book catalog="Programming"> <title lang="en">C++ Programming Language</title> <author>Bjarne Stroustrup</author> <year>1998</year> <price>98.0</price> </book> <book catalog="Networking"> <title lang="en">TCP/IP Illustrated</title> <author>Richard Stevens</author> <year>1996</year> <price>56.0</price> </book> </bookstore>
反序列化测试:
@Test public void test_XML2Obj(){ Serializer serializer = new Persister(); try { Bookstore bs = serializer.read(Bookstore.class, new File("F:/simple_xml.xml")); for(Book b : bs.getBook()){ System.out.println(b.getMap()); System.out.println(b.getAuthor()); System.out.println(b.getCatalog()); System.out.println(b.getPrice()); System.out.println(b.getYear()); } } catch (Exception e) { e.printStackTrace(); } }
比dom4j oo了许多.