用Simple framework OO的操作XML..

具体信息参见: 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了许多.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值