使用Dom4j

来源:互联网 发布:矩阵的长度 编辑:程序博客网 时间:2024/05/29 16:33
package cn.juni.test;


import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;


import cn.juni.bean.Student;
import cn.juni.bean.Teacher;
import cn.juni.util.ParseXMLUtil;


public class XMLTest {


public static void main(String[] args) throws Exception {
// dom4jCreate();
// parseXML2();

ParseXMLUtil pu = new ParseXMLUtil();
pu.parse("test.xml");
Student stu = (Student)pu.getClassById("id_s");
stu.show();

Teacher t = (Teacher)pu.getClassByCls(Teacher.class);
t.show();
}

public static void parseXML() throws Exception{
//获得dom解析器工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//获取dom解析器
DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
//解析XML文档,得到document对象
Document document = db.parse(new File("./src/test.xml"));
// Element element = document.getElementById("test_id");
NodeList nodeList = document.getElementsByTagName("bean");
/*for(int i=0;i<nodeList.getLength();i++){
System.out.println(nodeList.item(i).getNodeName());
System.out.println(nodeList.item(i).getNodeValue());
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}*/

//获取某节点所有的属性--返回一个NamedNodeMap集合
NamedNodeMap map = nodeList.item(0).getAttributes();

if(null != map){
for(int i=0;i<map.getLength();i++){
//获取Attr对象
Attr attr = (Attr)map.item(i);
//获取节点名称
String name = attr.getName();
//获取节点值
String value = attr.getValue();

System.out.println(name+"----"+value);

}
}
}
/**
* 使用dom4j创建XML
* @throws IOException 
*/
public static void dom4jCreate() throws IOException{
/*//创建并设置文档根节点 方式一:
org.dom4j.Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("student");
document.setRootElement(root);*/

//方式二:
Element root = DocumentHelper.createElement("student");
org.dom4j.Document document = DocumentHelper.createDocument(root);

//给根节点添加属性及值
root.addAttribute("id", "c_student");
root.addAttribute("class", "cn.juni.test.createelement");

//给student节点添加子节点
Element nameElement = root.addElement("name");
Element ageElement = root.addElement("age");

//给子节点添加属性及值
nameElement.addAttribute("type", "string");
nameElement.addAttribute("value", "张三");

ageElement.addAttribute("type", "Integer");
ageElement.addAttribute("value", "20");

//进行写操作---在控制台输出
XMLWriter writer = new XMLWriter();
writer.write(document);

OutputFormat format = new OutputFormat("  ", true);

//将节点通过字节流写入到自定义的文件中
XMLWriter writer2 = new XMLWriter(new FileOutputStream("Student.xml"),format);
writer2.write(document);

//将节点通过字符流写入到自定义的文件中
XMLWriter writer3 = new XMLWriter(new FileWriter(new String("Student2.xml".getBytes(),"gbk")),format);
writer3.write(document);
writer3.close();
}
/**
* 使用dom4j解析XML
* @throws DocumentException 
*/
public static void parseXML2() throws DocumentException{
//创建Map集合存放节点名称及内容(可能是节点,所以值为Object)
Map<String, Object> elMap = new HashMap<>();
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取XML文件获取Document对象
org.dom4j.Document document = reader.read(new File("Student.xml"));
//获取根节点
Element element = document.getRootElement();
//获取所有的一级子节点
List<Element> listElement = element.elements();
//遍历所有的一级子节点 将节点名及内容放到Map集合中
//想要遍历所有的子节点,将该方法抽离进行递归即可
for(Element el : listElement){
elMap.put(el.getName(), el.getTextTrim());
}
//获取Set集合泛型为Map.Entry类型方便遍历
Set<Map.Entry<String, Object>> entry = elMap.entrySet();
//得到对应的迭代器
Iterator<Map.Entry<String, Object>> iterator = entry.iterator();

while(iterator.hasNext()){
Map.Entry<String, Object> mEntry = iterator.next();
System.out.println(mEntry.getKey()+"---"+mEntry.getValue());
}
}

}



package cn.juni.util;


import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class ParseXMLUtil {


//创建Map数组将ID与CLASS作为键值对存储
Map<String,Object> map = null;

public void parse(String filePath) throws Exception{
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取XML文件获取Document对象
Document document = reader.read(new File(filePath));
//获取根节点
Element element = document.getRootElement();
//获取所有的一级子节点
List<Element> listElement = element.elements();

map = new HashMap<String,Object>();

for(Element el : listElement){
Attribute attrVal = el.attribute("class");
Attribute attrKey = el.attribute("id");

//获取class值
String value = attrVal.getValue();
//获取ID值
String key = attrKey.getValue();

if(null!=value){
//class值不为空则通过反射得到Object对象存储到Map集合中
Class cls = Class.forName(value);
Object obj = cls.newInstance();
map.put(key, obj);
}
}
System.out.println(map);
}

/**
* 通过ID查找对应的类,并返回该对象
* @param beanId
* @param map
* @return
*/
public Object getClassById(String beanId){
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
Object obj = null;
while(it.hasNext()){
String key = it.next();
//ID匹配则通过KEY得到对象并返回
if(beanId.equals(key)){
obj = map.get(key);
return obj;
}
}
return null;
}

/**
* 通过类文件查找对应的类,并返回该对象
* @param cls
* @param map
* @return
* @throws IllegalAccessException 
* @throws InstantiationException 
*/
public Object getClassByCls(Class cls) throws InstantiationException, IllegalAccessException{
//从Map集合中得到的对象
Object mCls = null;
if(null != map){
//得到Set集合
Set<Map.Entry<String, Object>> setEntry = map.entrySet();
//得到迭代器
Iterator<Map.Entry<String, Object>> it = setEntry.iterator();

while(it.hasNext()){
Map.Entry<String, Object> entry = it.next();
//获取集合中的value(存储的Object对象)
mCls = entry.getValue();
//判断是否是同一个Class文件,是则返回该对象
if(mCls.getClass() == cls){
return mCls;
}
}
}
return null;
}
}


public class Student {

private String name;
private int age;

public Student(){}

public void show(){
System.out.println("--Student--show--");
}
}



public class Teacher {

private String name;
private int age;

public Teacher(){}

public void show(){
System.out.println("--Teacher--show--");
}
}