package com.wuage.wechat.service;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import com.wuage.wechat.entity.ReceiveXmlEntity;
/**
* 类JdomXmlProcess.java的实现描述:TODO 类实现描述
*
* @author wangpeng 2016年9月15日 上午12:05:14
*/
public class JdomXmlProcess {
public static ReceiveXmlEntity parseXml(String xml) throws JDOMException, IOException {
ReceiveXmlEntity msg = null;
/** *创建一个新的字符串*** */
StringReader xmlReader = new StringReader(xml);
/** **创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 */
InputSource xmlSource = new InputSource(xmlReader);
/** *创建一个SAXBuilder* */
SAXBuilder builder = new SAXBuilder();
/** *通过输入源SAX构造一个Document** */
Document doc = builder.build(xmlSource);
/** *获得根节点** */
Element root = doc.getRootElement();
/** *获得BODY节点** */
List
list = root.getChildren();
Class
c = null;
try {
c = Class.forName("com.wuage.wechat.entity.ReceiveXmlEntity");
msg = (ReceiveXmlEntity) c.newInstance();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建这个实体的对象
/** *遍历出body节点下面所有的子节点,节点名称和内容用put到map* */
for (Element childEle : list) {
try {
// 获取set方法中的参数字段(实体类的属性)
Field field = c.getDeclaredField(childEle.getName());
// 获取set方法,field.getType())获取它的参数数据类型
Method method = c.getDeclaredMethod("set" + childEle.getName(), field.getType());
// 调用set方法
method.invoke(msg, childEle.getText());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// map.put(childEle.getName(), childEle.getText());
}
return msg;
}
}
jdom解析xml
最新推荐文章于 2024-10-09 16:29:08 发布