註解+反射+遞歸動態生成多層XML
註釋xml幫助類
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
-
@auther QiaoZhenwu
-
@date 2017年8月9日 下午5:16:00
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface XmlHelper {}
2.下面我們多創建幾個實體類,並且使它們通過@XmlHelper的註解聯系起來,代碼如下:
import java.util.List;
/**
-
@auther QiaoZhenwu
-
@date 2017年8月9日 下午4:53:35
*/
public class Child {
private String name; private String age; @XmlHelper private List<ChildToChild> childToChilds; @XmlHelper private Child2 child2; public Child2 getChild2() { return child2; } public void setChild2(Child2 child2) { this.child2 = child2; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public List<ChildToChild> getChildToChilds() { return childToChilds; } public void setChildToChilds(List<ChildToChild> childToChilds) { this.childToChilds = childToChilds; }
}
/**
-
@auther QiaoZhenwu
-
@date 2017年8月10日 下午5:16:56
*/
public class Child2 {
private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }
}
/**
-
@auther QiaoZhenwu
-
@date 2017年8月10日 上午10:38:54
*/
public class ChildToChild {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
/**
-
@auther QiaoZhenwu
-
@date 2017年8月9日 下午4:53:26
*/
public class Parent {
private String name;
private String age;
@XmlHelper
private Child child;
@XmlHelper
private ParentToParent parentToParent;
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public ParentToParent getParentToParent() {
return parentToParent;
}
public void setParentToParent(ParentToParent parentToParent) {
this.parentToParent = parentToParent;
}
}
/**
-
@auther QiaoZhenwu
-
@date 2017年8月10日 下午4:44:26
*/
public class ParentToParent {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
3.下面我們寫一下xml的生成和測試類,代碼如下:
xml生成和測試類
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSON;
/**
-
@auther QiaoZhenwu
-
@date 2017年8月9日 下午4:54:43
*/
public class TestMain {
public static void main(String[] args) throws DocumentException {
List<ChildToChild> childToChilds = new ArrayList<ChildToChild>();
ChildToChild ctc = new ChildToChild();
ctc.setAge("8");
ctc.setName("ctc1");
ChildToChild ctc2 = new ChildToChild();
ctc2.setAge("8");
ctc2.setName("ctc2");
childToChilds.add(ctc);
childToChilds.add(ctc2);
Child2 c2 = new Child2();
c2.setAge("c18");
c2.setName("c2");
Child c = new Child();
c.setAge("18");
c.setName("C");
c.setChildToChilds(childToChilds);
c.setChild2(c2);
ParentToParent ptp = new ParentToParent();
ptp.setAge("p48");
ptp.setName("ptp");
Parent p = new Parent();
p.setAge("48");
// p.setName("P");
p.setChild(c);
p.setParentToParent(ptp);
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("xml");
Element eles = root.addElement("interface");
eles.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
eles.addAttribute("xsi:schemaLocation", "http://www.chinatax.gov.cn/tirip/dataspec/interfaces.xsd");
eles.addAttribute("version", "DZFP1.0");
getbean(p, eles, "Child");
String reqBody = "<?xml version=‘1.0‘ encoding=‘utf-8‘ ?>"
+ doc.getRootElement().asXML();
System.out.println(reqBody);
Document document=DocumentHelper.parseText(reqBody);
Element r=document.getRootElement();
Map<String, Object> map = ParseXml.getMap(r, r.nodeCount());
System.out.println(JSON.toJSONString(map));
}
/**
* 生成xml
* @param o
* @param root
*/
public static void getbean(Object o, Element root, String name) {
Class<? extends Object> cls = o.getClass();
try {
// 得到自定義的屬性
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
// 獲取屬性
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cls);
Method getMethod = pd.getReadMethod();// 獲得get方法
Object ob = getMethod.invoke(o);// 執行get方法返回一個Object
// System.out.println(f.getName() + ":" + f.getType().getName() + " = " + JSON.toJSONString(ob));
XmlHelper xh = f.getAnnotation(XmlHelper.class);//獲取帶有@XmlHelper註解的實體
if (xh != null) {
if(name != null && !"".equals(name) && name.equals(o.getClass().getSimpleName())){
if(f.getType().getName().equals("java.util.List") && ((List)ob).size() > 0){
Element eles = root.addElement(f.getName());
eles.addAttribute("class", f.getName().substring(0, f.getName().length() - 1));
eles.addAttribute("size", ((List)ob).size() + "");
for(int i = 0; i < ((List)ob).size(); i++){
Object os = ((List)ob).get(i);
Element ele = eles.addElement(os.getClass().getSimpleName());//添加xml標簽
getbean(os, ele, name);//遞歸 註解類繼續解析
}
}else{
Element ele = root.addElement(f.getName());
ele.addAttribute("class", f.getName());
String getMeName = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
Method actionMethod = cls.getDeclaredMethod(getMeName);
// 執行這個方法
Object obj = actionMethod.invoke(o);
getbean(obj, ele, name);//遞歸 註解類繼續解析
}
}else{
Element ele = root.addElement(f.getName());
String getMeName = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
Method actionMethod = cls.getDeclaredMethod(getMeName);
// 執行這個方法
Object obj = actionMethod.invoke(o);
getbean(obj, ele, name);//遞歸 註解類繼續解析
}
} else {
if(ob != null){
root.addElement(f.getName()).addText(JSON.toJSONString(ob).replace("\"", ""));
}else{
root.addElement(f.getName());
}
}
}
} catch (Exception e) {
}
}
}
4.xml解析類
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSON;
/**
-
@auther QiaoZhenwu
-
@date 2017年8月17日 下午2:20:03
*/
public class ParseXml {
public static Map<String, Object> getMap(Element e, int cnt){
Map<String, Object> map = new HashMap<String, Object>();
int count = cnt;
for(int j = 0; j < count; j++){
if(null != e.node(j).getName()){
Element el = e.element(e.node(j).getName());
if(el.getText() == null || "".equals(el.getText())){
Map<String, Object> ma = getMap(el,el.nodeCount());
map.put(e.node(j).getName(), ma);
}else{
map.put(el.getName(), el.getText());
}
}
}
return map;
}
}
註解+反射+遞歸動態生成多層XML