1.什么叫XML建模
将XML配置文件中的元素、属性、文本信息转换成对象的过程叫做XML建模
2. XML建模
1)根据XML配置文件元素节点创建元素节点实体类
ConfigModel、ActionModel、ForwardModel
2)利用dom4j+xpath技术实现XML建模
ConfigModelFactory
思路:
1)xml文件config.xml
2)根据XML中元素节点情况(DTD)来定义ConfigModel、ActionModel、ForwardModel对象模型
A.config节点下有多个子action节点,无节点属性
B.action节点下有多个子forward节点,有节点属性
C.forward下无子节点,有节点属性
3)使用Map集合存放子节点元素,其中key为子节点唯一属性,value为整个子节点对象
4)利用工厂模式+dom4j+xpath解析Xml配置文件
package com.zking.zy.entity;
import java.io.Serializable;
import java.util.HashMap;
/**
* xml文件action对象模型
* @author Administrator
*
*/
import java.util.Map;
public class Action implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1636025796139944593L;
private String path;
private String type;
private Map<String, Forward> map = new HashMap<String, Forward>();
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Action [path=" + path + ", type=" + type + ", map=" + map + "]";
}
public Action() {
}
/**
* 增加到map
*/
public void add(Forward f) {
map.put(f.getName(), f);
}
/**
* 查看
* @param name
* @return
*/
public Forward cx(String name) {
return map.get(name);
}
}
package com.zking.zy.util;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.zking.zy.entity.Action;
import com.zking.zy.entity.Config;
import com.zking.zy.entity.Forward;
public class Gc {//建模工厂
private static final String PATHTH = "/config.xml";//要建模的xml文件
private Gc() {
}
public static Config createC(String path) {
Config f = new Config();
String ppath = null;
String type = null;
String name = null;
String pppath = null;
String redirect= null;
Action acton = null;
Forward fo = null;
InputStream is = Gc.class.getResourceAsStream(path);
SAXReader sr = new SAXReader();
try {
Document d = sr.read(is);
//action节点
List<Node> ls = d.selectNodes("/config/action");
for (Node node : ls) {
Element e = (Element)node;
ppath = e.attributeValue("path");
type = e.attributeValue("type");
acton = new Action();
acton.setPath(ppath);
acton.setType(type);
List<Node> lsls = node.selectNodes("forward");
for (Node node2 : lsls) {
Element e2 = (Element)node2;//把节点转成元素拿xml文件属性
name = e2.attributeValue("name");
pppath = e2.attributeValue("path");
redirect = e2.attributeValue("redirect");
fo = new Forward();
fo.setName(name);
fo.setPath(pppath);
fo.setRedirect(Boolean.parseBoolean(redirect));
acton.add(fo);
}
f.add(acton);//通过方法把字节点放进集合
}
} catch (DocumentException e) {
e.printStackTrace();
}
return f;
}
public static Config createC() {
return createC(PATHTH);
}
}