xml文本格式是网络通信中最常用的格式,最近特别研究了一下如何解析xml文本并转换为对象,现在分享一下我最近的学习成果~
先列一下本例中需要解析的xml文本:
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>
讲一下我的思路,我选择使用XStream来解析xml文本,因为xstream在转换对象方面会比dom4j更优秀一些,它是通过注解方式来声明对应结点的,在操作上会更直观方便。首先会将整个文本转换成一个Results类对象,而每一个row结点作为一个HashMap放入到Results类对象的List列表中,最后会将每一个HashMap读取出来通过JAVA的反射机制转换为Info对象,并生成List列表。下载
Info类代码 
publicclassInfo{
privateStringid;
privateStringtitle;
privateStringcontent;
privateStringauthor;
privateStringpubtime;
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(Stringcontent){
this.content=content;
}
publicStringgetAuthor(){
returnauthor;
}
publicvoidsetAuthor(Stringauthor){
this.author=author;
}
publicStringgetPubtime(){
returnpubtime;
}
publicvoidsetPubtime(Stringpubtime){
this.pubtime=pubtime;
}
@Override
publicStringtoString(){
return"Info[author="+author+",content="+content+",id="+id
+",pubtime="+pubtime+",title="+title+"]";
}
}
Row类代码
@XStreamConverter(RowConverter.class)
publicclassRowextendsHashMap<String,String>{
privatestaticfinallongserialVersionUID=5619951409573339302L;
}下载
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);
}
下载
@Override
publicvoidmarshal(Objectarg0,HierarchicalStreamWriterwriter,
MarshallingContextarg2){
//TODOAuto-generatedmethodstub
Rowmap=(Row)arg0;
for(Iteratoriterator=map.entrySet().iterator();iterator.hasNext();){
Map.Entryentry=(Map.Entry)iterator.next();
writer.addAttribute(entry.getKey().toString(),entry.getValue().toString());
}
}
@Override
publicObjectunmarshal(HierarchicalStreamReaderreader,
UnmarshallingContextcontext){
//TODOAuto-generatedmethodstub
Rowmap=newRow();
populateMap(reader,context,map);
returnmap;
}
protectedvoidpopulateMap(HierarchicalStreamReaderreader,UnmarshallingContextcontext,Rowmap){
Iterator<String>iterator=reader.getAttributeNames();
while(iterator.hasNext()){
Objectkey=iterator.next();
Stringvalue=reader.getAttribute((String)key);
map.put(key.toString(),value.toString());
}
}
}
RowConverter是一个转换器类,作用是将每一个row结点转变一个HashMap。
测试类下载:
Java代码 
publicclassXstream{
privatestaticStringxml;
staticvoidmain(String[]args)throwsException{
init();
XStreamxstream=newXStream(newXppDriver(newXmlFriendlyReplacer("_-","_")));
xstream.processAnnotations(Results.class);
Resultsresults=(Results)xstream.fromXML(xml);
List<Info>list=createList(Info.class,results);
for(inti=0;i<list.size();i++){
Infoinfo=list.get(i);
System.out.println(info.toString());
}
}
voidinit(){
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>";
}
static<T>ListcreateList(Class<T>clz,Resultsresults)throwsException{
Listlist=newArrayList();
for(Rowrow:results.getRows()){
list.add(createObject(clz,row));
}
returnlist;
}
static<T>TcreateObject(Class<T>clazz,Rowrow)//初始化对象
Tobj=clazz.newInstance();
for(Methodmethod:clazz.getDeclaredMethods()){
StringmethodName=method.getName();
Class[]perams=method.getParameterTypes();
if(methodName.startsWith("set")&&methodName.length()>3&&perams.length==1){
Stringtemp=methodName.substring(3,methodName.length());
StringfieldName=temp.toLowerCase();
Stringvalue=row.get(fieldName);
if(value!=null){
ClassparamClass=perams[0];
if(String.class.equals(paramClass)){
method.invoke(obj,value);
}elseif(Integer.class.equals(paramClass)||int.}if(Long.long.class.equals(paramClass)){下载
method.invoke(obj,Long.valueOf(value));
}if(BigDecimal.newBigDecimal(value));
}if(Boolean.boolean.class.equals(paramClass)){
if(value.equals("true")||value.equals("TRUE"))
method.invoke(obj,85);font-weight:bold;">true);
if(value.equals("false")||value.equals("FALSE"))
method.invoke(obj,85);font-weight:bold;">false);
}
}
}
}
returnobj;
}
}
最后是输出效果:
Java代码
Info[author=APP,content=公告,是公开宣告。,id=140,pubtime=2016-04-1316:40:13,title=什么是公告]
Info[author=网站,content=12345678,0);">138,0);">36:50,title=12345678]
Info[author=网站,content=关于用户注册流程说明,0);">134,0);">0615:02:44,title=关于网站用户注册流程说明1]
Info[author=APP,content=测试,0);">126,0);">03-3018:32:Info[author=网站,0);">123,0);">125,0);">29:26,title=关于手机App使用说明]
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|