package com.softeem.xml.util;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.softeem.xml.dto.ClassDTO;
import com.softeem.xml.dto.CollegeDTO;
import com.softeem.xml.dto.StudentDTO;
public class SAXParseXML {
public static void main(String[] args) throws Exception {
String path = "D:/stus.xml";
CollegeDTO college = saxParse(path);
System.out.println(college.getClasses().get("计科1班").getStus().get("20111114").getStuName());
}
public static CollegeDTO saxParse(String path){
CollegeDTO college = null;
try {
SAXReader reader = new SAXReader();
//解析目标文件
Document dom = reader.read(new File(path));
//获取根节点
Element root = dom.getRootElement();
//获取根节点属性
// Attribute attr = root.attribute("id");
// String attrValue = attr.getValue();
// String cid = root.attribute("id").getValue();
String cid = root.attributeValue("id");
String cname = root.attributeValue("name");
//获取根节点的子节点
List<Element> cses = root.elements("class");
Map<String, ClassDTO> classes = new HashMap<String, ClassDTO>();
for (int i = 0; i < cses.size(); i++) {
Element cse = cses.get(i);
String className = cse.attributeValue("className");
String classNum = cse.attributeValue("classNum");
List<Element> stes = cse.elements("student");
Map<String, StudentDTO> stus = new HashMap<String, StudentDTO>();
for (Element ste : stes) {
String stuNum = ste.attributeValue("stuNum");
String stuName = ste.attributeValue("stuName");
String stuSex = ste.attributeValue("stuSex");
String stuAge = ste.attributeValue("stuAge");
StudentDTO stu = new StudentDTO(stuNum, stuName, stuSex, Integer.parseInt(stuAge));
stus.put(stuNum, stu);
}
ClassDTO cla = new ClassDTO(className, Integer.parseInt(classNum), stus);
classes.put(className, cla);
}
college = new CollegeDTO(Integer.parseInt(cid), cname, classes);
} catch (Exception e) {
System.err.println("出现错误!");
}
return college;
}
}<!--stus.xml文件--> <?xml version="1.0" encoding="UTF-8"?> <college id="1001" name=""> <class className="计科1班" classNum="41"> <student stuNum="20111111" stuName="" stuSex="男" stuAge="20" /> <student stuNum="20111112" stuName="" stuSex="男" stuAge="21" /> <student stuNum="20111113" stuName="" stuSex="女" stuAge="20" /> <student stuNum="20111114" stuName="" stuSex="男" stuAge="19" /> </class> <class className="网工1班" classNum="49"> <student stuNum="20112111" stuName="" stuSex="男" stuAge="21" /> <student stuNum="20112112" stuName="" stuSex="男" stuAge="20" /> <student stuNum="20112113" stuName="" stuSex="女" stuAge="22" /> </class> </college>
本文出自 “黑足Sanji” 博客,谢绝转载!
原文:http://974124461.blog.51cto.com/8685015/1546148