XStream解析XML文本并用反射机制转换为对象

前端之家收集整理的这篇文章主要介绍了XStream解析XML文本并用反射机制转换为对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

xml文本格式是网络通信中最常用的格式,最近特别研究了一下如何解析xml文本并转换为对象,现在分享一下我最近的学习成果~@H_502_1@

先列一下本例中需要解析的xml文本:@H_502_1@

Xml代码

收藏代码

@H_502_1@
  1. <resultsname="list">@H_502_1@

  2. rowpubtime="2016-04-1316:40:13"author="APP"id="140"title="什么是公告"content="公告,是公开宣告。"/>@H_502_1@

  3. rowpubtime="2016-04-1316:36:50"author="网站"id="138"title="12345678"content="12345678"rowpubtime="2016-04-0615:02:44"author="网站"id="134"title="关于网站用户注册流程说明1"content="关于用户注册流程说明"rowpubtime="2016-03-3018:32:13"author="APP"id="126"title="关于网站使用说明"content="测试"rowpubtime="2016-03-3018:29:26"author="网站"id="125"title="关于手机App使用说明"content="123"</results>@H_502_1@

@H_502_1@

讲一下我的思路,我选择使用XStream来解析xml文本,因为xstream在转换对象方面会比dom4j更优秀一些,它是通过注解方式来声明对应结点的,在操作上会更直观方便。首先会将整个文本转换成一个Results类对象,而每一个row结点作为一个HashMap放入到Results类对象的List列表中,最后会将每一个HashMap读取出来通过JAVA的反射机制转换为Info对象,并生成List列表。下载@H_502_1@

@H_502_1@

Info类代码

收藏代码

@H_502_1@
  1. publicclassInfo{@H_502_1@

  2. @H_502_1@

  3. privateStringid;@H_502_1@

  4. privateStringtitle;@H_502_1@

  5. privateStringcontent;@H_502_1@

  6. privateStringauthor;@H_502_1@

  7. privateStringpubtime;@H_502_1@

  8. publicStringgetId(){@H_502_1@

  9. returnid;@H_502_1@

  10. }@H_502_1@

  11. publicvoidsetId(Stringid){@H_502_1@

  12. this.id=id;@H_502_1@

  13. }@H_502_1@

  14. publicStringgetTitle(){@H_502_1@

  15. returntitle;@H_502_1@

  16. }@H_502_1@

  17. publicvoidsetTitle(Stringtitle){@H_502_1@

  18. this.title=title;@H_502_1@

  19. }@H_502_1@

  20. publicStringgetContent(){@H_502_1@

  21. returncontent;@H_502_1@

  22. }@H_502_1@

  23. publicvoidsetContent(Stringcontent){@H_502_1@

  24. this.content=content;@H_502_1@

  25. }@H_502_1@

  26. publicStringgetAuthor(){@H_502_1@

  27. returnauthor;@H_502_1@

  28. }@H_502_1@

  29. publicvoidsetAuthor(Stringauthor){@H_502_1@

  30. this.author=author;@H_502_1@

  31. }@H_502_1@

  32. publicStringgetPubtime(){@H_502_1@

  33. returnpubtime;@H_502_1@

  34. }@H_502_1@

  35. publicvoidsetPubtime(Stringpubtime){@H_502_1@

  36. this.pubtime=pubtime;@H_502_1@

  37. }@H_502_1@

  38. @Override@H_502_1@

  39. publicStringtoString(){@H_502_1@

  40. return"Info[author="+author+",content="+content+",id="+id@H_502_1@

  41. +",pubtime="+pubtime+",title="+title+"]";@H_502_1@

  42. }@H_502_1@

  43. @H_502_1@

  44. @H_502_1@

  45. @H_502_1@

  46. }@H_502_1@

@H_502_1@

Row类代码

  • @XStreamConverter(RowConverter.class)

  • publicclassRowextendsHashMap<String,String>{

  • privatestaticfinallongserialVersionUID=5619951409573339302L;

  • }下载@H_502_1@

  • @H_502_1@

    Results代码

  • @XStreamAlias("results")

  • publicclassResults{

  • @XStreamAlias("name")

  • @XStreamAsAttribute

  • privateStringname;

  • @XStreamImplicit(itemFieldName="row")

  • privateList<Row>rows;

  • publicStringgetName(){

  • returnname;

  • }

  • publicvoidsetName(Stringname){

  • this.name=name;

  • }

  • publicList<Row>getRows(){

  • returnrows;

  • }

  • publicvoidsetRows(List<Row>rows){

  • this.rows=rows;

  • }

  • }

  • Rowconverter类代码

  • publicclassRowConverterextendsAbstractCollectionConverter{

  • publicRowConverter(Mappermapper){

  • super(mapper);

  • //TODOAuto-generatedconstructorstub

  • }

  • @Override

  • publicbooleancanConvert(Classarg0){

  • //TODOAuto-generatedmethodstub

  • returnRow.class.equals(arg0);

  • }

  • 下载@H_502_1@

  • @Override@H_502_1@

  • publicvoidmarshal(Objectarg0,HierarchicalStreamWriterwriter,@H_502_1@

  • MarshallingContextarg2){@H_502_1@

  • //TODOAuto-generatedmethodstub@H_502_1@

  • Rowmap=(Row)arg0;@H_502_1@

  • for(Iteratoriterator=map.entrySet().iterator();iterator.hasNext();){@H_502_1@

  • Map.Entryentry=(Map.Entry)iterator.next();@H_502_1@

  • writer.addAttribute(entry.getKey().toString(),entry.getValue().toString());@H_502_1@

  • }@H_502_1@

  • }@H_502_1@

  • @H_502_1@

  • @Override@H_502_1@

  • publicObjectunmarshal(HierarchicalStreamReaderreader,@H_502_1@

  • UnmarshallingContextcontext){@H_502_1@

  • //TODOAuto-generatedmethodstub@H_502_1@

  • Rowmap=newRow();@H_502_1@

  • populateMap(reader,context,map);@H_502_1@

  • returnmap;@H_502_1@

  • }@H_502_1@

  • @H_502_1@

  • protectedvoidpopulateMap(HierarchicalStreamReaderreader,UnmarshallingContextcontext,Rowmap){@H_502_1@

  • Iterator<String>iterator=reader.getAttributeNames();@H_502_1@

  • while(iterator.hasNext()){@H_502_1@

  • Objectkey=iterator.next();@H_502_1@

  • Stringvalue=reader.getAttribute((String)key);@H_502_1@

  • map.put(key.toString(),value.toString());@H_502_1@

  • }@H_502_1@

  • }@H_502_1@

  • }@H_502_1@

  • RowConverter是一个转换器类,作用是将每一个row结点转变一个HashMap。@H_502_1@

    测试类下载:@H_502_1@

    Java代码

    收藏代码

    @H_502_1@
    1. publicclassXstream{@H_502_1@

    2. @H_502_1@

    3. privatestaticStringxml;@H_502_1@

    4. @H_502_1@

    5. staticvoidmain(String[]args)throwsException{@H_502_1@

    6. //初始化@H_502_1@

    7. init();@H_502_1@

    8. @H_502_1@

    9. XStreamxstream=newXStream(newXppDriver(newXmlFriendlyReplacer("_-","_")));@H_502_1@

    10. //解析xml文本@H_502_1@

    11. xstream.processAnnotations(Results.class);@H_502_1@

    12. Resultsresults=(Results)xstream.fromXML(xml);@H_502_1@

    13. //将解析出来的Results类对象转化成list列表@H_502_1@

    14. List<Info>list=createList(Info.class,results);@H_502_1@

    15. @H_502_1@

    16. for(inti=0;i<list.size();i++){@H_502_1@

    17. //打印@H_502_1@

    18. Infoinfo=list.get(i);@H_502_1@

    19. System.out.println(info.toString());@H_502_1@

    20. }@H_502_1@

    21. @H_502_1@

    22. }@H_502_1@

    23. voidinit(){@H_502_1@

    24. //初始化xml文本@H_502_1@

    25. xml="<resultsname=\"list\"><rowpubtime=\"2016-04-1316:40:13\"author=\"APP\"id=\"140\"title=\"什么是公告\"content=\"公告,是公开宣告。\"/><rowpubtime=\"2016-04-1316:36:50\"author=\"网站\"id=\"138\"title=\"12345678\"content=\"12345678\"/><rowpubtime=\"2016-04-0615:02:44\"author=\"网站\"id=\"134\"title=\"关于网站用户注册流程说明1\"content=\"关于用户注册流程说明\"/><rowpubtime=\"2016-03-3018:32:13\"author=\"APP\"id=\"126\"title=\"关于网站使用说明\"content=\"测试\"/><rowpubtime=\"2016-03-3018:29:26\"author=\"网站\"id=\"125\"title=\"关于手机App使用说明\"content=\"123\"/></results>";@H_502_1@

    26. }@H_502_1@

    27. static<T>ListcreateList(Class<T>clz,Resultsresults)throwsException{@H_502_1@

    28. Listlist=newArrayList();@H_502_1@

    29. for(Rowrow:results.getRows()){@H_502_1@

    30. //根据class和Row生成对象放入list@H_502_1@

    31. list.add(createObject(clz,row));@H_502_1@

    32. @H_502_1@

    33. }@H_502_1@

    34. returnlist;@H_502_1@

    35. }@H_502_1@

    36. static<T>TcreateObject(Class<T>clazz,Rowrow)//初始化对象@H_502_1@

    37. Tobj=clazz.newInstance();@H_502_1@

    38. //遍历Info类中所有方法@H_502_1@

    39. for(Methodmethod:clazz.getDeclaredMethods()){@H_502_1@

    40. StringmethodName=method.getName();@H_502_1@

    41. Class[]perams=method.getParameterTypes();@H_502_1@

    42. //找到set开头,长度大于3,并且入参数量为1的方法@H_502_1@

    43. if(methodName.startsWith("set")&&methodName.length()>3&&perams.length==1){@H_502_1@

    44. @H_502_1@

    45. Stringtemp=methodName.substring(3,methodName.length());@H_502_1@

    46. //拿到属性名称@H_502_1@

    47. StringfieldName=temp.toLowerCase();@H_502_1@

    48. //根据属性名称从HashMap中拿到对应的值@H_502_1@

    49. Stringvalue=row.get(fieldName);@H_502_1@

    50. @H_502_1@

    51. if(value!=null){@H_502_1@

    52. //拿到该方法入参的Class,根据入参类型来决定调用方法形式@H_502_1@

    53. ClassparamClass=perams[0];@H_502_1@

    54. if(String.class.equals(paramClass)){@H_502_1@

    55. method.invoke(obj,value);@H_502_1@

    56. }elseif(Integer.class.equals(paramClass)||int.502_1@

    57. }if(Long.long.class.equals(paramClass)){下载@H_502_1@

    58. method.invoke(obj,Long.valueOf(value));@H_502_1@

    59. }if(BigDecimal.newBigDecimal(value));@H_502_1@

    60. }if(Boolean.boolean.class.equals(paramClass)){@H_502_1@

    61. if(value.equals("true")||value.equals("TRUE"))@H_502_1@

    62. method.invoke(obj,85);font-weight:bold;">true);@H_502_1@

    63. if(value.equals("false")||value.equals("FALSE"))@H_502_1@

    64. method.invoke(obj,85);font-weight:bold;">false);@H_502_1@

    65. }@H_502_1@

    66. }@H_502_1@

    67. @H_502_1@

    68. }@H_502_1@

    69. }@H_502_1@

    70. returnobj;@H_502_1@

    71. }@H_502_1@

    72. }@H_502_1@

    最后是输出效果:@H_502_1@

    Java代码

  • Info[author=APP,content=公告,是公开宣告。,id=140,pubtime=2016-04-1316:40:13,title=什么是公告]@H_502_1@

  • Info[author=网站,content=12345678,0);">138,0);">36:50,title=12345678]@H_502_1@

  • Info[author=网站,content=关于用户注册流程说明,0);">134,0);">0615:02:44,title=关于网站用户注册流程说明1]@H_502_1@

  • Info[author=APP,content=测试,0);">126,0);">03-3018:32:502_1@

  • Info[author=网站,0);">123,0);">125,0);">29:26,title=关于手机App使用说明] @H_502_1@

  • 猜你在找的XML相关文章