之前想写一个JAXB解析xml与实体类转换的,但是发现JAXB有一定的局限性,有时,在解析非标准xml中的属性值时,不能够获取到其中的值,很奇怪的是,JAXB是jdk中自带的API,竟然在AndroidStudio环境中竟然不能使用,引入jar包也会报错,后索性改为用SAX解析,并对其进行了一定的封装,只需要传入几个简单的参数即可得到想要的实体类。
如果你的需求是根据解析xml返回一个简单对象集合,那么来这就对了。
何为简单对象,即这个对象的成员类型属于基本数据类型,当然了Date也可以,你只需要添加相关注解将字符串转换成date就行了;不含有自定义类
1. 简单介绍SAX
SAX(Simple API for XML)解析器是一种基于事件的解析器,它的核心是事件处理模式,主要是围绕着事件源以及事件处理器来工作的。当事件源产生事件后,调用事件处理器相应的处理方法,一个事件就可以得到处理。在事件源调用事件处理器中特定方法的时候,还要传递给事件处理器相应事件的状态信息,这样事件处理器才能够根据提供的事件信息来决定自己的行为。
SAX解析器的优点是解析速度快,占用内存少。非常适合在Android移动设备中使用
2. 列出要解析的数据(数据来源:http://wcf.open.cnblogs.com/news/hot/10)
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">博客园新闻频道</title>
<id>uuid:400dd255-fe1f-4cc3-bebd-bbe2e47f2c0f;id=49744</id>
<updated>2017-04-09T10:13:38Z</updated>
<link href="http://news.cnblogs.com/" />
<entry>
<id>566495</id>
<title type="text">老外两张漫画实力黑Linux版SQL Server</title>
<summary type="text">
Linux 版 SQL Server(一)在 Linux 内核之中,大家正在静静的等待进程的创建。每个创建的进程会被分配一个进程 ID (PID)。在那个 Apache 进程高高兴兴的走出去之后,下一位却被要求创建 Linux 版的 SQL Server,这简直让人气的跳...
</summary>
<published>2017-04-06T09:22:33+08:00</published>
<updated>2017-04-09T10:13:38Z</updated>
<link rel="alternate" href="http://news.cnblogs.com/n/566495/" />
<diggs>16</diggs>
<views>4542</views>
<comments>20</comments>
<topic />
<topicIcon>http://images0.cnblogs.com/news_topic///images0.cnblogs.com/news_topic/sqlserver.gif</topicIcon>
<sourceName>linux.cn</sourceName>
</entry>
<entry>
<id>566335</id>
<title type="text">IBM都叫停SOHO办公了!创业公司还要犯这大忌?</title>
<summary type="text">
SOHO 办公一度是个十分流行的概念。据美国民意调查机构 Gallup poll 统计,美国每四个人中就有一个人选择 SOHO 办公。中国创业者最崇拜的就是自由式、咖啡厅式的谷歌办公环境。但现在,即使是一些以创新和开放著称的大公司,也开始逐渐召回自己的 SOHO 员工,让他们...
</summary>
<published>2017-04-04T16:50:41+08:00</published>
<updated>2017-04-09T10:13:38Z</updated>
<link rel="alternate" href="http://news.cnblogs.com/n/566335/" />
<diggs>6</diggs>
<views>3866</views>
<comments>11</comments>
<topic />
<topicIcon>http://images0.cnblogs.com/news_topic///images0.cnblogs.com/news_topic/ibm.gif</topicIcon>
<sourceName>虎嗅网</sourceName>
</entry>
</feed>
3. 从上面数据我们可以看出,主要是要entry中的值,所以根据entry内容,我们得到以下实体类:
/**
* Created by zml2015 on 2017/4/8 20:16.
*/
public class BKYNews {
<span class="hljs-keyword">private</span> String id;
<span class="hljs-keyword">private</span> String title;
<span class="hljs-comment">/**
* 总结,新闻概述
*/</span>
<span class="hljs-keyword">private</span> String summary;
<span class="hljs-comment">/**
* 发布时间
*/</span>
<span class="hljs-keyword">private</span> String published;
<span class="hljs-comment">/**
* 更新时间
*/</span>
<span class="hljs-keyword">private</span> String updated;
<span class="hljs-keyword">private</span> String link_href;
<span class="hljs-comment">/**
* 推荐次数(点赞次数)
*/</span>
<span class="hljs-keyword">private</span> String diggs;
<span class="hljs-comment">/**
* 浏览量
*/</span>
<span class="hljs-keyword">private</span> String views;
<span class="hljs-comment">/**
* 评论数
*/</span>
<span class="hljs-keyword">private</span> String comments;
<span class="hljs-comment">/**
* 话题图标,这里的网址有问题,这里的网址有一部分是重复的,只需要截取“///”之后的内容然后前篇拼接“http://”即可
*/</span>
<span class="hljs-keyword">private</span> String topicIcon;
<span class="hljs-comment">/**
* 新闻来源
*/</span>
<span class="hljs-keyword">private</span> String sourceName;
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> id;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(String id)</span> </span>{
<span class="hljs-keyword">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getTitle</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> title;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTitle</span><span class="hljs-params">(String title)</span> </span>{
<span class="hljs-keyword">this</span>.title = title;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSummary</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> summary;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSummary</span><span class="hljs-params">(String summary)</span> </span>{
<span class="hljs-keyword">this</span>.summary = summary;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPublished</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> published;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPublished</span><span class="hljs-params">(String published)</span> </span>{
<span class="hljs-keyword">this</span>.published = published;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getUpdated</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> updated;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUpdated</span><span class="hljs-params">(String updated)</span> </span>{
<span class="hljs-keyword">this</span>.updated = updated;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDiggs</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> diggs;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDiggs</span><span class="hljs-params">(String diggs)</span> </span>{
<span class="hljs-keyword">this</span>.diggs = diggs;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getViews</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> views;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setViews</span><span class="hljs-params">(String views)</span> </span>{
<span class="hljs-keyword">this</span>.views = views;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getComments</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> comments;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setComments</span><span class="hljs-params">(String comments)</span> </span>{
<span class="hljs-keyword">this</span>.comments = comments;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getTopicIcon</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> topicIcon;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTopicIcon</span><span class="hljs-params">(String topicIcon)</span> </span>{
<span class="hljs-keyword">this</span>.topicIcon = topicIcon;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSourceName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> sourceName;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSourceName</span><span class="hljs-params">(String sourceName)</span> </span>{
<span class="hljs-keyword">this</span>.sourceName = sourceName;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getLink_href</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> link_href;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setLink_href</span><span class="hljs-params">(String link_href)</span> </span>{
<span class="hljs-keyword">this</span>.link_href = link_href;
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"BKYNews{"</span> +
<span class="hljs-string">"id='"</span> + id + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", title='"</span> + title + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", summary='"</span> + summary + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", published='"</span> + published + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", updated='"</span> + updated + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", link='"</span> + link_href + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", diggs='"</span> + diggs + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", views='"</span> + views + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", comments='"</span> + comments + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", topicIcon='"</span> + topicIcon + <span class="hljs-string">'\''</span> +
<span class="hljs-string">", sourceName='"</span> + sourceName + <span class="hljs-string">'\''</span> +
<span class="hljs-string">'}'</span>;
}
}
4. 给出的实体类的规则是:
* 属性名与要解析的xml的标签名一致
* 如果要解析标签中的属性值,则命名规则为:标签名+下划线+ 属性名
> 如上面给出的实体类中一个属性名叫`link_href`,即是xml中link标签中的href属性
* 暂只支持标签2层(要解析的数据有两层,而不是要解析的数据在整个xml数据中有多少层)
嵌套,不支持标签多层嵌套,(如entry标签中有author,author标签中有name),稍后我会尝试写一个,如有大神解救,甚是欢喜
* 实体类名称与要解析的标签名称不一致没有关系,因为需要将要解析的根标签传入,如,我们要解析的数据是entry标签中的内容,所以要传入entry
5. 给出SAX最最重要的解析过程,这个是个工具类中的内容,可直接拷贝,无须修改
/**
* @author zml2015
* @Email zhengmingliang911@gmail.com
* @Time 2017年4月9日 下午2:58:36
* @Description <p>用于解析xml为实体类的处理器 </P>
* @version 1.0
*/
class XMlHandler<T> extends DefaultHandler{
String rootElemntName;
Map<String, String> dataMap;
StringBuilder stringBuilder;
List<T> dataList;
T data;
Class<T> clz;
private Map<String,Class> attrs;
<span class="hljs-comment">/**
* <span class="hljs-doctag">@author</span> zml2015
* <span class="hljs-doctag">@Email</span> zhengmingliang911<span class="hljs-doctag">@gmail</span>.com
* <span class="hljs-doctag">@Time</span> 2017年4月9日 下午3:13:43
* <span class="hljs-doctag">@Description</span> <p> 当前标签名称 </P>
* <span class="hljs-doctag">@version</span> 1.0
*/</span>
<span class="hljs-keyword">private</span> String currentTag;
<span class="hljs-comment">/**
* 要解析的单个实体的根元素名称
* <span class="hljs-doctag">@param</span> rootElemntName
* <span class="hljs-doctag">@throws</span> IllegalAccessException
* <span class="hljs-doctag">@throws</span> InstantiationException
*/</span>
XMlHandler(String rootElemntName,Class<T> clz,Map<String,Class> attrsMap) {
<span class="hljs-keyword">this</span>.rootElemntName = rootElemntName;
<span class="hljs-keyword">this</span>.clz = clz;
<span class="hljs-keyword">this</span>.attrs = attrsMap;
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">startDocument</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> SAXException </span>{
<span class="hljs-keyword">super</span>.startDocument();
dataMap = <span class="hljs-keyword">new</span> HashMap<String, String>();
stringBuilder = <span class="hljs-keyword">new</span> StringBuilder();
dataList = <span class="hljs-keyword">new</span> ArrayList<>();
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">startElement</span><span class="hljs-params">(String uri, String localName, String qName, Attributes attributes)</span> <span class="hljs-keyword">throws</span> SAXException </span>{
<span class="hljs-comment">// TODO Auto-generated method stub</span>
<span class="hljs-keyword">super</span>.startElement(uri, localName, qName, attributes);
<span class="hljs-comment">//赋值给当前标签名称</span>
currentTag = qName;
<span class="hljs-keyword">if</span> (rootElemntName.equals(qName)) {
<span class="hljs-keyword">try</span> {
data = clz.newInstance();
} <span class="hljs-keyword">catch</span> (InstantiationException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IllegalAccessException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
}
<span class="hljs-comment">//每次对一个标签解析前,都先置为空</span>
stringBuilder.setLength(<span class="hljs-number">0</span>);
<span class="hljs-comment">//如果某个标签中有属性,则将其保存到map中,保存规则:key = “标签名称_属性名称” value = “属性值”</span>
<span class="hljs-keyword">if</span>(attributes != <span class="hljs-keyword">null</span> && dataMap != <span class="hljs-keyword">null</span>){
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < attributes.getLength(); i++) {
dataMap.put(qName+<span class="hljs-string">"_"</span>+attributes.getQName(i), attributes.getValue(i));
}
}
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">characters</span><span class="hljs-params">(<span class="hljs-keyword">char</span>[] ch, <span class="hljs-keyword">int</span> start, <span class="hljs-keyword">int</span> len)</span> <span class="hljs-keyword">throws</span> SAXException </span>{
<span class="hljs-comment">// TODO Auto-generated method stub</span>
<span class="hljs-keyword">super</span>.characters(ch, start, len);
stringBuilder.append(ch,start,len);
Field[] fields = clz.getDeclaredFields();
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">if</span> (StringUtils.isNotEmpty(currentTag) && data != <span class="hljs-keyword">null</span>) {
<span class="hljs-keyword">for</span> (Field field : fields) {
String name = field.getName();
<span class="hljs-keyword">if</span> (currentTag.equals(name)) {
name = name.substring(<span class="hljs-number">0</span>,<span class="hljs-number">1</span>).toUpperCase() + name.substring(<span class="hljs-number">1</span>);
Method method = data.getClass().getMethod(<span class="hljs-string">"set"</span>+name, field.getType());
method.invoke(data, stringBuilder.toString());
}
}
}
} <span class="hljs-keyword">catch</span> (NoSuchMethodException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (SecurityException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IllegalAccessException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IllegalArgumentException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (InvocationTargetException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">endElement</span><span class="hljs-params">(String uri, String localName, String qName)</span> <span class="hljs-keyword">throws</span> SAXException </span>{
<span class="hljs-keyword">super</span>.endElement(uri, localName, qName);
<span class="hljs-keyword">if</span> (rootElemntName.equals(qName)) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">if</span> (attrs != <span class="hljs-keyword">null</span>) {
<span class="hljs-keyword">for</span> (String attrName : attrs.keySet()) {
String methodName = <span class="hljs-string">"set"</span>+attrName.substring(<span class="hljs-number">0</span>,<span class="hljs-number">1</span>).toUpperCase()+attrName.substring(<span class="hljs-number">1</span>);
Method method = data.getClass().getMethod(methodName,attrs.get(attrName));
method.invoke(data, dataMap.get(attrName));
}
}
} <span class="hljs-keyword">catch</span> (NoSuchMethodException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (SecurityException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IllegalAccessException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IllegalArgumentException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (InvocationTargetException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
dataList.add(data);
}
}
<span class="hljs-annotation">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">endDocument</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> SAXException </span>{
System.out.println(<span class="hljs-string">"解析结束:"</span>+dataList);
<span class="hljs-keyword">super</span>.endDocument();
}
<span class="hljs-function"><span class="hljs-keyword">public</span> List<T> <span class="hljs-title">getDataList</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">return</span> dataList;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getData</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">return</span> data;
}
}
6. 工具类:主要看工具类的最后一个方法:parseXml2Bean,前面方法均是JAXB对xml与对象转换的方法
import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import top.wys.developerclub.model.SysUser;
import top.wys.developerclub.test.BKYAticle;
public class XmlUtils {
<span class="hljs-comment">/**
* <span class="hljs-doctag">@author</span> zml2015
* <span class="hljs-doctag">@Time</span> 2017年4月1日19:04:50
* <span class="hljs-doctag">@Description</span> <p>
* 将实体类直接转换成xml
* </p>
* <span class="hljs-doctag">@param</span> t
* 要转换成xml的对象
* <span class="hljs-doctag">@return</span> xml字符串
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <T> <span class="hljs-function">String <span class="hljs-title">createXmlFromBean</span><span class="hljs-params">(T t)</span> </span>{
String xml = <span class="hljs-string">""</span>;
<span class="hljs-keyword">if</span> (t == <span class="hljs-keyword">null</span>) {
<span class="hljs-keyword">return</span> xml;
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">try</span> (StringWriter write = <span class="hljs-keyword">new</span> StringWriter()) {
JAXBContext context = JAXBContext.newInstance(t.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, <span class="hljs-keyword">true</span>);
marshaller.marshal(t, write);
xml = write.toString();
} <span class="hljs-keyword">catch</span> (JAXBException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IOException e1) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e1.printStackTrace();
}
<span class="hljs-keyword">return</span> xml;
}
}
<span class="hljs-comment">/**
* <span class="hljs-doctag">@author</span> zml2015
* <span class="hljs-doctag">@Time</span> 2017年4月1日19:04:50
* <span class="hljs-doctag">@Description</span> <p>
* 将实体类直接转换成xml,要转换的类必需加油<span class="hljs-doctag">@XmlRootElement</span>注解
* </p>
* <span class="hljs-doctag">@param</span> t
* 要转换成xml的对象
* <span class="hljs-doctag">@param</span> format 是否格式化输出,{<span class="hljs-doctag">@code</span> true}格式化输出,{<span class="hljs-doctag">@code</span> false} 不进行格式化
* <span class="hljs-doctag">@return</span> xml字符串
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <T> <span class="hljs-function">String <span class="hljs-title">createXmlFromBean</span><span class="hljs-params">(T t,<span class="hljs-keyword">boolean</span> format)</span> </span>{
String xml = <span class="hljs-string">""</span>;
<span class="hljs-keyword">if</span> (t == <span class="hljs-keyword">null</span>) {
<span class="hljs-keyword">return</span> xml;
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">try</span> (StringWriter write = <span class="hljs-keyword">new</span> StringWriter()) {
<span class="hljs-comment">// 利用jdk中自带的转换类实现</span>
JAXBContext context = JAXBContext.newInstance(t.getClass());
Marshaller marshaller = context.createMarshaller();
<span class="hljs-comment">// 格式化xml输出的格式 </span>
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
<span class="hljs-comment">// 将对象转换成xml写入到StringWriter中</span>
marshaller.marshal(t, write);
xml = write.toString();
} <span class="hljs-keyword">catch</span> (JAXBException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IOException e1) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e1.printStackTrace();
}
<span class="hljs-keyword">return</span> xml;
}
}
<span class="hljs-comment">/**
* <span class="hljs-doctag">@author</span> zml2015
* <span class="hljs-doctag">@Time</span> 2017年4月1日19:04:50
* <span class="hljs-doctag">@Description</span> <p>
* 将实体类直接转换成xml,要转换的类必需加油<span class="hljs-doctag">@XmlRootElement</span>注解
* </p>
* <span class="hljs-doctag">@param</span> t 要转换成xml的对象
*
* <span class="hljs-doctag">@param</span> filePath 要保存到的文件路径
* <span class="hljs-doctag">@return</span> xml字符串
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <T> <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">createXmlToFile</span><span class="hljs-params">(T t,String filePath)</span> </span>{
<span class="hljs-keyword">try</span> (FileWriter write = <span class="hljs-keyword">new</span> FileWriter(filePath)) {
<span class="hljs-comment">// 利用jdk中自带的转换类实现</span>
JAXBContext context = JAXBContext.newInstance(t.getClass());
Marshaller marshaller = context.createMarshaller();
<span class="hljs-comment">// 格式化xml输出的格式 </span>
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, <span class="hljs-keyword">true</span>);
<span class="hljs-comment">// 将对象转换成xml写入到StringWriter中</span>
marshaller.marshal(t, write);
} <span class="hljs-keyword">catch</span> (JAXBException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IOException e1) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e1.printStackTrace();
}
}
<span class="hljs-annotation">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <T> <span class="hljs-function">T <span class="hljs-title">getBeanFromXml</span><span class="hljs-params">(String xml, Class<T> clz)</span> </span>{
T t = <span class="hljs-keyword">null</span>;
<span class="hljs-keyword">try</span> (StringReader reader = <span class="hljs-keyword">new</span> StringReader(xml);) {
JAXBContext context = JAXBContext.newInstance(clz);
Unmarshaller unmarshal = context.createUnmarshaller();
t = (T) unmarshal.unmarshal(reader);
} <span class="hljs-keyword">catch</span> (JAXBException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
<span class="hljs-keyword">return</span> t;
}
<span class="hljs-annotation">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <T> <span class="hljs-function">T <span class="hljs-title">getBeanFromXml</span><span class="hljs-params">(InputStream is, Class<T> clz)</span> </span>{
T t = <span class="hljs-keyword">null</span>;
<span class="hljs-keyword">try</span>{
JAXBContext context = JAXBContext.newInstance(SysUser.class);
Unmarshaller unmarshal = context.createUnmarshaller();
t = (T) unmarshal.unmarshal(is);
} <span class="hljs-keyword">catch</span> (JAXBException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
<span class="hljs-keyword">return</span> t;
}
<span class="hljs-comment">/**
* <span class="hljs-doctag">@author</span> zml2015
* <span class="hljs-doctag">@Email</span> zhengmingliang911<span class="hljs-doctag">@gmail</span>.com
* <span class="hljs-doctag">@Time</span> 2017年4月9日 下午6:32:02
* <span class="hljs-doctag">@Description</span> <p> 将xml转换为指定对象 </P>
* <span class="hljs-doctag">@param</span> xml 要解析的xml数据
* <span class="hljs-doctag">@param</span> rootElemntName 要解析的内容的根标签名称
* <span class="hljs-doctag">@param</span> clz 要转换成的实体类,
* <span class="hljs-doctag">@param</span> attrs key值为要解析的xml标签中的属性值, value 值为属性值类型
* <span class="hljs-doctag">@return</span>
*/</span>
<span class="hljs-keyword">public</span> <T> <span class="hljs-function">List<T> <span class="hljs-title">parseXml2Bean</span><span class="hljs-params">(String xml,String rootElemntName,Class<T> clz,Map<String, Class> attrs)</span></span>{
XMlHandler<T> handler = <span class="hljs-keyword">null</span>;
<span class="hljs-keyword">try</span>(ByteArrayInputStream stream = <span class="hljs-keyword">new</span> ByteArrayInputStream(xml.getBytes());) {
handler = <span class="hljs-keyword">new</span> XMlHandler<>(rootElemntName, clz, attrs);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(stream, handler);
System.out.println(handler.getDataList());
} <span class="hljs-keyword">catch</span> (ParserConfigurationException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (SAXException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
} <span class="hljs-keyword">catch</span> (IOException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
<span class="hljs-keyword">return</span> handler.getDataList();
}
}
7. 测试类:
@Test
public void testXML2Model1() throws IOException {
String xml = HttpUtils.getHttpData("http://wcf.open.cnblogs.com/news/hot/10");
Map<String,Class> map = new HashMap<>();
map.put("link_href", String.class);
List<BKYAticle> list = parseXml2Bean(xml,"entry", BKYAticle.class,map);
}</code></pre>
8. 效果图
点次查看完整大图(一定要找到中间那条线,然后在上面放大查看哦)
Q.E.D.