工具类
/** * 将xml解析为指定对象 * * @param clazz 相关的类 * @param <T> 转化后的类 * @return */ public static <T> T parseXmlToBean(String url, Class[] clazz, Class<T> target) throws Exception { XStream xs = new XStream(new DomDriver("UTF-8")); //忽略object中没有的标签 xs.ignoreUnknownElements(); //所有相关的object xs.processAnnotations(clazz); //类型转换 xs.registerConverter(new XmlDateConverter()); xs.autodetectAnnotations(true); //过滤掉特殊符号:官方定义了XML的无效字符分为三段(0x00 - 0x08、0x0b - 0x0c、0x0e - 0x1f) StringBuilder result = HttpClientUtils.doGet(url); if (StringUtils.isNotBlank(result)) { return (T) xs.fromXML(result.toString().replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "")); } return null; }
调用的方式:
RssXml rssXml = XmlUtil.parseXmlToBean(zhuanlan.getRssAddress(), new Class[]{RssXml.class, RssXmlChannel.class, RssXmlItem.class}, RssXml.class);
相关的类:
@Setter @Getter @XStreamAlias("rss") public class RssXml { @XStreamAlias("channel") private RssXmlChannel channel; } @Setter @Getter @XStreamAlias("channel") public class RssXmlChannel{ /** * 标题 */ @XStreamAlias("title") private String title; /** * 内容 */ @XStreamImplicit(itemFieldName = "item") private List<RssXmlItem> item; } @Setter @Getter @XStreamAlias("item") public class RssXmlItem { /** * 标题 */ private String title; /** * 内容 */ @XStreamAlias("content:encoded") private String content; /** * 发行时间 */ @XStreamConverter(value = XmlDateConverter.class) private Date pubDate; /** * 附件 */ private XmlEnclosure enclosure; /** * 图片地址 */ @XStreamAlias("itunes:image") private XmlImage image; /** * 图片信息 */ @Getter @Setter @XStreamAlias("itunes:image") public class XmlImage { @XStreamAsAttribute String href;//标签的属性 } /** * 附件信息 */ @Getter @Setter @XStreamAlias("enclosure") public class XmlEnclosure { //标签的属性 @XStreamAsAttribute private String url; @XStreamAsAttribute private String type; @XStreamAsAttribute private int length; } }
日期转化方法
/** * 转换RSS的xml时间类型 * */ public class XmlDateConverter extends AbstractSingleValueConverter { @Override public boolean canConvert(Class type) { return type.equals(Date.class); } @Override public Date fromString(String str) { // 这里将字符串转换成日期 try { if (StringUtils.isBlank(str)) { return new Date(); } return new Date(str); } catch (Exception e) { e.printStackTrace(); return null; } } }
相关jar包:
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.16</version> </dependency>