XStream解析[以支付宝解析为列子]

XStream 

 Xstream是一种OXMapping 技术,是用来处理XML文件序列化的框架,在将JavaBean序列化,或将XML文件反序列化的时候,不需要其它辅助类和映射文件,使得XML序列化不再繁索。Xstream也可以将JavaBean序列化成Json或反序列化,使用非常方便。

首先介绍几个常用的注解:

1.@XStreamAlias("")  别名,对应xml中节点名称

2.@XStreamAsAttribute   把字段节点设置成属性

3.@XStreamImplicit 省略集合根节点,当遇到list集合可以使用此注解.

4.@XStreamOmitField 隐藏字段 

5.设置转换器:@XStreamConverter()

列:

  1. @XStreamConverter(value=BooleanConverter.class,booleans={false},strings={"男","女"})
  2. privateboolean sex;

下面贴上使用xstream解析支付宝账单xml实列


1首先建立entity

package xmlParser.xStream;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;

/**
 * 支付宝查询账单接口 xml实体类
 * 
 */
@XStreamAlias("alipay")
public class AlipayAccountPageQuery {

	@XStreamAlias("is_success")
	private String isSuccess;

	@XStreamAlias("error")
	private String error;

	@XStreamAlias("request")
	private Request request;

	@XStreamAlias("response")
	private Response response;

	public static class Request {

		@XStreamImplicit(itemFieldName = "param")
		private List<Param> param;

		public List<Param> getParam() {
			return param;
		}

		public void setParam(List<Param> param) {
			this.param = param;
		}

	}

	@XStreamAlias("param")
	@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "content" })
	public static class Param {
		public Param(String name, String content) {
			super();
			this.name = name;
			this.content = content;
		}

		@XStreamAsAttribute
		private String name;

		private String content;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getContent() {
			return content;
		}

		public void setContent(String content) {
			this.content = content;
		}

	}

	public static class Response {

		@XStreamAlias("account_page_query_result")
		private Account_page_query_result account_page_query_result;

		public Account_page_query_result getAccount_page_query_result() {
			return account_page_query_result;
		}

		public void setAccount_page_query_result(
				Account_page_query_result account_page_query_result) {
			this.account_page_query_result = account_page_query_result;
		}

	}

	public static class Account_page_query_result {
		@XStreamAlias("has_next_page")
		private String has_next_page; // 是否有下一页
		@XStreamAlias("page_no")
		private Integer page_no; // 当前页
		@XStreamAlias("page_size")
		private String page_size; // 当前页大小

		@XStreamAlias("account_log_list")
		private Account_log_list account_log_list; // 账单数据

		public String getHas_next_page() {
			return has_next_page;
		}

		public void setHas_next_page(String has_next_page) {
			this.has_next_page = has_next_page;
		}

		public Integer getPage_no() {
			return page_no;
		}

		public void setPage_no(Integer page_no) {
			this.page_no = page_no;
		}

		public String getPage_size() {
			return page_size;
		}

		public void setPage_size(String page_size) {
			this.page_size = page_size;
		}

		public Account_log_list getAccount_log_list() {
			return account_log_list;
		}

		public void setAccount_log_list(Account_log_list account_log_list) {
			this.account_log_list = account_log_list;
		}

	}

	public static class Account_log_list {
		// @XStreamAlias("AccountQueryAccountLogVO")
		@XStreamImplicit(itemFieldName = "AccountQueryAccountLogVO")
		private ArrayList<AccountQueryAccountLogVO> accountQueryAccountLogVO;

		public ArrayList<AccountQueryAccountLogVO> getAccountQueryAccountLogVO() {
			return accountQueryAccountLogVO;
		}

		public void setAccountQueryAccountLogVO(
				ArrayList<AccountQueryAccountLogVO> accountQueryAccountLogVO) {
			this.accountQueryAccountLogVO = accountQueryAccountLogVO;
		}

	}

	public static class AccountQueryAccountLogVO {

		@XStreamAlias("balance")
		private Double balance; // 余额
		@XStreamAlias("buyer_account")
		private String buyer_account; // 买家支付宝账号
		@XStreamAlias("currency")
		private String currency; // 货币代码
		@XStreamAlias("deposit_bank_no")
		private String deposit_bank_no; // 充值网银流水号
		@XStreamAlias("goods_title")
		private String goods_title; // 商品名称
		@XStreamAlias("income")
		private Double income; // 收入金额
		@XStreamAlias("iw_account_log_id")
		private String iw_account_log_id; // 支付宝财务序列号
		@XStreamAlias("memo")
		private String memo; // 备注
		@XStreamAlias("merchant_out_order_no")
		private String merchant_out_order_no; // 商户订单号
		@XStreamAlias("outcome")
		private Double outcome; // 支出金额
		@XStreamAlias("partner_id")
		private String partner_id; // 合作者身份id
		@XStreamAlias("rate")
		private String rate; // 费率
		@XStreamAlias("seller_account")
		private String seller_account; // 卖家支付宝账号
		@XStreamAlias("seller_fullname")
		private String seller_fullname; // 卖家姓名
		@XStreamAlias("service_fee")
		private Double service_fee; // 交易服务费
		@XStreamAlias("service_fee_ratio")
		private String service_fee_ratio; // 交易服务费率
		@XStreamAlias("sign_product_name")
		private String sign_product_name; // 签约产品
		@XStreamAlias("sub_trans_code_msg")
		private String sub_trans_code_msg; // 子业务类型
		@XStreamAlias("total_fee")
		private Double total_fee; // 交易总金额
		@XStreamAlias("trade_no")
		private String trade_no; // 支付宝交易号
		@XStreamAlias("trade_refund_amount")
		private Double trade_refund_amount; // 累计退款金额
		@XStreamAlias("trans_code_msg")
		private String trans_code_msg; // 业务类型
		@XStreamAlias("trans_date")
		private String trans_dateString;
		private Date trans_date;// 交易付款时间

		public Double getBalance() {
			return balance;
		}

		public void setBalance(Double balance) {
			this.balance = balance;
		}

		public String getBuyer_account() {
			return buyer_account;
		}

		public void setBuyer_account(String buyer_account) {
			this.buyer_account = buyer_account;
		}

		public String getCurrency() {
			return currency;
		}

		public void setCurrency(String currency) {
			this.currency = currency;
		}

		public String getDeposit_bank_no() {
			return deposit_bank_no;
		}

		public void setDeposit_bank_no(String deposit_bank_no) {
			this.deposit_bank_no = deposit_bank_no;
		}

		public String getGoods_title() {
			return goods_title;
		}

		public void setGoods_title(String goods_title) {
			this.goods_title = goods_title;
		}

		public Double getIncome() {
			return income;
		}

		public void setIncome(Double income) {
			this.income = income;
		}

		public String getIw_account_log_id() {
			return iw_account_log_id;
		}

		public void setIw_account_log_id(String iw_account_log_id) {
			this.iw_account_log_id = iw_account_log_id;
		}

		public String getMemo() {
			return memo;
		}

		public void setMemo(String memo) {
			this.memo = memo;
		}

		public String getMerchant_out_order_no() {
			return merchant_out_order_no;
		}

		public void setMerchant_out_order_no(String merchant_out_order_no) {
			this.merchant_out_order_no = merchant_out_order_no;
		}

		public Double getOutcome() {
			return outcome;
		}

		public void setOutcome(Double outcome) {
			this.outcome = outcome;
		}

		public String getPartner_id() {
			return partner_id;
		}

		public void setPartner_id(String partner_id) {
			this.partner_id = partner_id;
		}

		public String getRate() {
			return rate;
		}

		public void setRate(String rate) {
			this.rate = rate;
		}

		public String getSeller_account() {
			return seller_account;
		}

		public void setSeller_account(String seller_account) {
			this.seller_account = seller_account;
		}

		public String getSeller_fullname() {
			return seller_fullname;
		}

		public void setSeller_fullname(String seller_fullname) {
			this.seller_fullname = seller_fullname;
		}

		public Double getService_fee() {
			return service_fee;
		}

		public void setService_fee(Double service_fee) {
			this.service_fee = service_fee;
		}

		public String getService_fee_ratio() {
			return service_fee_ratio;
		}

		public void setService_fee_ratio(String service_fee_ratio) {
			this.service_fee_ratio = service_fee_ratio;
		}

		public String getSign_product_name() {
			return sign_product_name;
		}

		public void setSign_product_name(String sign_product_name) {
			this.sign_product_name = sign_product_name;
		}

		public String getSub_trans_code_msg() {
			return sub_trans_code_msg;
		}

		public void setSub_trans_code_msg(String sub_trans_code_msg) {
			this.sub_trans_code_msg = sub_trans_code_msg;
		}

		public Double getTotal_fee() {
			return total_fee;
		}

		public void setTotal_fee(Double total_fee) {
			this.total_fee = total_fee;
		}

		public String getTrade_no() {
			return trade_no;
		}

		public void setTrade_no(String trade_no) {
			this.trade_no = trade_no;
		}

		public Double getTrade_refund_amount() {
			return trade_refund_amount;
		}

		public void setTrade_refund_amount(Double trade_refund_amount) {
			this.trade_refund_amount = trade_refund_amount;
		}

		public String getTrans_code_msg() {
			return trans_code_msg;
		}

		public void setTrans_code_msg(String trans_code_msg) {
			this.trans_code_msg = trans_code_msg;
		}

		public Date getTrans_date() {
			return strToDate(trans_dateString);
		}

		public String getTrans_dateString() {
			return trans_dateString;
		}

		public void setTrans_dateString(String trans_dateString) {
			this.trans_dateString = trans_dateString;
		}

		public void setTrans_date(Date trans_date) {
			this.trans_date = trans_date;
		}

		@Override
		public String toString() {
			return "AccountQueryAccountLogVO [balance=" + balance
					+ ", buyer_account=" + buyer_account + ", currency="
					+ currency + ", deposit_bank_no=" + deposit_bank_no
					+ ", goods_title=" + goods_title + ", income=" + income
					+ ", iw_account_log_id=" + iw_account_log_id + ", memo="
					+ memo + ", merchant_out_order_no=" + merchant_out_order_no
					+ ", outcome=" + outcome + ", partner_id=" + partner_id
					+ ", rate=" + rate + ", seller_account=" + seller_account
					+ ", seller_fullname=" + seller_fullname + ", service_fee="
					+ service_fee + ", service_fee_ratio=" + service_fee_ratio
					+ ", sign_product_name=" + sign_product_name
					+ ", sub_trans_code_msg=" + sub_trans_code_msg
					+ ", total_fee=" + total_fee + ", trade_no=" + trade_no
					+ ", trade_refund_amount=" + trade_refund_amount
					+ ", trans_code_msg=" + trans_code_msg
					+ ", trans_dateString=" + trans_dateString
					+ ", trans_date=" + trans_date + "]";
		}

	}

	@XStreamAlias("sign")
	private String sign;

	@XStreamAlias("sign_type")
	private String sign_type;

	public String getIsSuccess() {
		return isSuccess;
	}

	public void setIsSuccess(String isSuccess) {
		this.isSuccess = isSuccess;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public String getSign_type() {
		return sign_type;
	}

	public void setSign_type(String sign_type) {
		this.sign_type = sign_type;
	}

	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public Response getResponse() {
		return response;
	}

	public void setResponse(Response response) {
		this.response = response;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	
	
	public static Date strToDate(String sStr) {
		if (sStr == null)
			return null;
		SimpleDateFormat formatter;
		if (sStr.length() == 28) {
			formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
			Date date;
			try {
				date = formatter.parse(sStr);
				DateFormat formatTo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				return formatTo.parse(formatTo.format(date));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else if (sStr.length() == 19) {
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		} else if (sStr.length() == 10) {
			formatter = new SimpleDateFormat("yyyy-MM-dd");
		} else if (sStr.length() == 8) {
			formatter = new SimpleDateFormat("yyyyMMdd");
		} else if(sStr.length() == 23){
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		} else if (sStr.length() == 14) {
			formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		} else {
			formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		}
		ParsePosition pos = new ParsePosition(0);
		// formatter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		return formatter.parse(sStr, pos);
	}
}

2.建立解析测试demo

package xmlParser.xStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlParser {
	public static <T> T XML2Bean(String xml, Class<T> clazz) throws IOException {

		XStream xstream = new XStream(new DomDriver());

		xstream.processAnnotations(clazz);
		return (T) xstream.fromXML(xml);
	}

	public static <T> T XML2Bean(InputStream input, Class<T> clazz)
			throws IOException {

		XStream xstream = new XStream(new DomDriver());

		xstream.processAnnotations(clazz);

		return (T) xstream.fromXML(input);
	}
	
	public static String XML2Bean(Object obj)
			throws IOException {

		XStream xstream = new XStream(new DomDriver());


		return  xstream.toXML(obj);
	}
	public static void main(String[] args) {
		InputStream inputStream=null;
		try {
			String path=Thread.currentThread().getContextClassLoader().getResource("").getPath();
			System.out.println(path);
			inputStream=new FileInputStream(new File(path+"\\xmlParser\\xStream\\ali.xml"));
			AlipayAccountPageQuery xml2Bean = XML2Bean(inputStream, AlipayAccountPageQuery.class);
			//任意打印一个字段值测试.
			System.out.println(xml2Bean.getRequest().getParam().get(0).getContent());
		
			// xml也可以反序列化
			String xml2Bean2 = XML2Bean(xml2Bean);
			System.out.println(xml2Bean2);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if (inputStream!=null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


至此解析完毕

相关代码和被解析的xml下载地址: http://download.csdn.net/detail/u012930316/9741700

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值