xstream+dom4j比较对象
package com.brmoney.util.obj2xml; import java.util.Iterator;
import java.util.List; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element; import com.brmoney.flight.pojo.DomeTicketPsg;
import com.brmoney.util.resource.FieldResourceBundle;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.converters.Converter; public class Object2Xml { static DomDriver domDriver = null;
static Converter xmlNullConverter = null; static {
domDriver = new DomDriver();
xmlNullConverter = new XmlNullConverter();
} public static String compare2Object(Object obj1, Object obj2)
throws DocumentException {
XStream stream = new XStream(domDriver);
stream.registerConverter(xmlNullConverter);
String xml1 = stream.toXML(obj1);
String xml2 = stream.toXML(obj2); Document doc1 = DocumentHelper.parseText(xml1);
Document doc2 = DocumentHelper.parseText(xml2); StringBuffer buffer = new StringBuffer();
List<Element> elements = doc1.selectNodes(obj1.getClass().getName());
List<Element> unElements = doc2.selectNodes(obj1.getClass().getName());
for (int i = 0; i < elements.size(); i++) {
Element rootElement = elements.get(i);
Element unRootElement = unElements.get(i);
if (rootElement != null && unRootElement != null) {
Iterator eles = rootElement.elementIterator();
Iterator unEles = unRootElement.elementIterator();
while (eles.hasNext() && unEles.hasNext()) {
Element e = (Element) eles.next();
Element ue = (Element) unEles.next();
if (e.getName().equals(ue.getName())
&& !e.getTextTrim().equals(ue.getTextTrim())) {
String[] config = FieldResourceBundle.getMessage(
e.getName(), obj1.getClass().getSimpleName())
.split("[|]");
if (config[0] != null) {
buffer.append(config[0]).append(":").append("由")
.append(e.getTextTrim()).append(
" 更改为: ")
.append(ue.getTextTrim()).append("\n");
}
}
}
} }
return buffer.toString();
} public static void main(String[] args) throws DocumentException {
DomeTicketPsg psg1 = new DomeTicketPsg();
psg1.setPsgName("项羽");
DomeTicketPsg psg2 = new DomeTicketPsg();
psg2.setPsgName("刘备"); System.out.print(Object2Xml.compare2Object(psg1, psg2)); } }
package com.brmoney.util.obj2xml; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /**
* 自定义XStream转化器,
* 使null值标签可以输出到XML
*/
@SuppressWarnings("unchecked")
public class XmlNullConverter implements Converter
{ private Map<Class<?>, List<String>> attributes = null; public void regAttribute(Class<?> type, String attribute)
{
if (null == attributes)
{
attributes = new HashMap<Class<?>, List<String>>();
} List value = attributes.get(type);
if (null == value)
{
value = new ArrayList<String>();
attributes.put(type, value);
} value.add(attribute);
} /**
* 是否是属性(是属性的不用以单独标签实现)
* @param type
* @param attribute
* @return
*/
private boolean isClassAttribute(Class<?> type, String attribute)
{
List<String> value = getAttributes(type);
if (null == value)
return false;
if (value.contains(attribute))
{
return true;
}
return false;
} /**
* 获取注册的属性
* @param type
* @return
*/
private List<String> getAttributes(Class<?> type)
{
if (null != attributes)
{
return attributes.get(type);
}
return null;
} /**
* 输出对象的属性标签
* @param source
* @param writer
*/
private void writerAttribute(Object source, HierarchicalStreamWriter writer)
{
Class cType = source.getClass();
List<String> value = getAttributes(cType);
if ((null != value) && (value.size() > 0))
{
Method[] methods = cType.getMethods();
for (Method method : methods)
{
String methodName = method.getName();
if (methodName.indexOf("get") != -1 && methodName != "getClass")
{
String name = methodName.substring(3);
//首字母小写
name = name.substring(0, 1).toLowerCase()+name.substring(1);
if (value.contains(name))
{
Object o = null;
try {
o = method.invoke(source, null);
} catch (Exception e) {
e.printStackTrace();
}
writer.addAttribute(name, o==null?"":o.toString());
}
}
}
}
} public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context)
{
if (null == source)
return;
if (isBaseType(source.getClass()))
{
return;
}
Class cType = source.getClass();
Method[] methods = cType.getMethods();
writerAttribute(source, writer);
for(Method m : methods)
{
String methodName = m.getName();
if (methodName.indexOf("get") != -1 && methodName != "getClass")
{
if (source instanceof List)
{
List list = (List)source;
for (Object obj: list)
{
String name = obj.getClass().toString();
name = name.substring(name.lastIndexOf(".") + 1); writer.startNode(name);
marshal(obj, writer, context);
writer.endNode();
}
}
else
{
boolean isBaseType = isBaseType(m.getReturnType());
String name = methodName.substring(3);
if (isBaseType)
{
name = name.substring(0, 1).toLowerCase()+name.substring(1);
}
Object o = null;
try
{
o = m.invoke(source, null);
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
}
//如果是基本类型调用toString,否则递归
if (isBaseType)
{
if (!isClassAttribute(cType, name))
{
writer.startNode(name);
if (m.getReturnType().equals(Date.class)&&o!=null&&!"".equals(o.toString()))
{
Date date = (Date)o;
DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,new Locale("zh", "CN"));
writer.setValue(formatter.format(date));
}else{
writer.setValue(o==null?"":o.toString());
}
writer.endNode();
}
}
else
{
writer.startNode(name);
marshal(o, writer, context);
writer.endNode();
}
}
}
}
} public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
return null;
} public boolean canConvert(Class type) {
return true;
} private boolean isBaseType(Class<?> type)
{
if (type.equals(Integer.class)
|| type.equals(Double.class)
|| type.equals(String.class)
|| type.equals(Boolean.class)
|| type.equals(Long.class)
||type.equals(Short.class)
||type.equals(Byte.class)
||type.equals(Float.class)
||type.equals(Date.class))
{
return true;
}
return false;
}
}
package com.brmoney.util.resource; import java.util.Locale;
import java.util.ResourceBundle; public class FieldResourceBundle { private static String baseKey = "datafield/"; public static String getMessage(String key,String propName){
Locale locale = new Locale("zh", "CN");
ResourceBundle bundle = ResourceBundle.getBundle(baseKey+propName, locale);
if(bundle.containsKey(key)){
return bundle.getString(key);
}
return "";
} }
xstream+dom4j比较对象的更多相关文章
- XStream将java对象转换为xml时,对象字段中的下划线“_”,转换后变成了两个的解决办法
在前几天的一个项目中,由于数据库字段的命名原因 其中有两项:一项叫做"市场价格"一项叫做"商店价格" 为了便于区分,遂分别将其命名为market ...
- Java对象表示方式2:XStream实现对对象的XML化
上一篇文章讲到了使用Java原生的序列化的方式来表示一个对象.总结一下这种对象表示方式的优缺点: 1.纯粹的Java环境下这种方式可以很好地工作,因为它是Java自带的,也不需要第三方的Jar包的支持 ...
- XStream转换Java对象与XML
1.引入需要的jar包,在pom.xml中配置依赖 <dependency> <groupId>com.thoughtworks.xstream</groupId> ...
- XStream类的对象将javaBean转成XML
[省市联动] servlet端: //返回数据xml(XStream) XStream xStream = new XStream(); //把路径设置别名 xStream.alias("c ...
- Spring Boot 使用 Dom4j XStream 操作 Xml
Xml 现在仍然占据着比较重要的地位,比如微信接口中使用了 Xml 进行消息的定义.本章重点讨论 Xml 的新建.编辑.查找.转化,可以这么理解,本章是使用了 dom4j.xstream 也是在开发者 ...
- 使用XStream是实现XML与Java对象的转换(6)--持久化
九.持久化 在第八节的示例中,当我们操作一组对象时,我们可以指定Writer.OutputStream来写出序列化后的XML数据,我们还可以指定Reader.InputStream来读取序列化后的XM ...
- 使用XStream是实现XML与Java对象的转换(1)--简介及入门示例
一.简单介绍 XStream是thoughtworks开发的开源框架,用于实现XML数据于Java对象.Json数据的转换.它不需要schema或其他的mapping文件就可以进行java对象和xml ...
- Javaweb学习笔记——(二十三)——————AJAX、XStream、JSON
AJAX概述 1.什么是AJAX ajax(Asynchronous JavaScript and xml) 翻译成中文就是"异步JavaScript和xml&quo ...
- atitit.XML类库选型及object 对象bean 跟json转换方案
atitit.XML类库选型及object 对象bean 跟json转换方案 1. XML类库可以分成2大类.标准的.这些类库通常接口和实现都是分开的 1 2. 常见的xml方面的方法 2 2.1. ...
随机推荐
- 浅析Dagger2依赖注入实现过程
Dragger2是Android应用开发中一个非常优秀的依赖注入框架.本文主要通过结合Google给出的MVP开发案例todo-mvp-dagger(GitHub连接地址:https://github ...
- World Wind Java开发之四——搭建本地WMS服务器(转)
在提供地理信息系统客户端时,NASA还为用户提供了开源的WMS Server 服务器应用:World Wind WMS Server.利用这个应用,我们可以架设自己的WMS服务并使用自己的数据(也支持 ...
- 模块化Java简介
什么是模块化? 模块化是个一般概念,这一概念也适用于软件开发,可以让软件按模块单独开发,各模块通常都用一个标准化的接口来进行通信.实际上,除了规模大小有区别外,面向对象语言中对象之间的关注点分离与 ...
- hdu-1198 Farm Irrigation---并查集+模拟(附测试数据)
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1198 题目大意: 有如上图11种土地块,块中的绿色线条为土地块中修好的水渠,现在一片土地由上述的各种 ...
- c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法&提示缺少“libmysql.dll”
课程作业要用c++连接mysql server,但是出现些小问题,经查阅资料已经解决,做一下笔记. 环境:vs2017, mysql版本是8.0.16-winx64. 设置项目属性 项目 - C ...
- 2018.6.19 Java核心API与高级编程实践复习总结
Java 核心编程API与高级编程实践 第一章 异常 1.1 异常概述 在程序运行中,经常会出现一些意外情况,这些意外会导致程序出错或者崩溃而影响程序的正常执行,在java语言中,将这些程序意外称为异 ...
- appium---adb通过wifi连接手机
前几天接到领导的安排,想要测试下apk的耗电量,可以通过手机adb命令进行监控手机电量的变化:但是这样如果通过USB连接手机的话,USB就会自动给手机进行充电,无法达到我们想要的结果,于是想到了通过w ...
- Python读取图片,并保存为矩阵
from scipy.misc import imread,imshow img = imread('D:test.bmp') print img[:,:,2].shape imshow() 注意im ...
- java中利用JOptionPane类弹出消息框的部分例子
转: http://www.cnblogs.com/wangxiuheng/p/4449917.html http://blog.csdn.net/penjie0418/article/details ...
- 搜狗浏览器特性页面JS
http://ie.sogou.com/features4.2.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN ...