我已用dom4J解析好了xml 接下来我要用反射将其放入实体类输出 该如何写?刚学反射的萌新求教
解析代码:
package com.xml;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4j2 {
private static Map<String,String> map=new HashMap<String,String>();
public static Map<String,String> parseXml(File filePath)throws DocumentException{
Map<String,String>mapEle=new HashMap<String,String>();
SAXReader reader=new SAXReader();
Document document=reader.read(filePath);
Element root=document.getRootElement();
List<Element>elementList=root.elements();
Iterator<Element> it=elementList.iterator();
while(it.hasNext()){
Element element=it.next();
mapEle=printEle(element);
}
return mapEle;
}
private static Map<String,String> printEle(Element ele) {
if(ele.elements().size()==0){
Element name=ele.getParent();
System.out.println(name.attributeValue("name")+"="+ele.getText());
map.put(ele.getParent().getName(), ele.getText());
System.out.println("\t");
}else{
List<Element>elementList=ele.elements();
Iterator<Element>it=elementList.iterator();
while(it.hasNext()){
printEle(it.next());
}
}
return map;
}
/**
* @param args
*/
public static void main(String[] args) {
File file =new File("src/res/peopleList.xml");
Map<String,String> mapELeList=new HashMap<String,String>();
try{
mapELeList=Dom4j2.parseXml(file);
Iterator<java.util.Map.Entry<String,String>> it=mapELeList.entrySet().iterator();
while(it.hasNext()){
java.util.Map.Entry<String,String> entry=it.next();
System.out.println(entry.getKey()+".."+entry.getValue());
}
}catch (DocumentException e) {
e.printStackTrace();
}
}
}
实体类
package com.xml;
public class People {
private String position;
private String name;
private String FullName;
private String dept;
private String role;
private String duty;
private String wkgp;
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty;
}
public String getWkgp() {
return wkgp;
}
public void setWkgp(String wkgp) {
this.wkgp = wkgp;
}
@Override
public String toString(){
return "people[position="+position+",name="+name+",FullName="+FullName+",dept="+dept+",role="+role+",duty="+duty+"]"+"\n";
}
}