Xml解析
一、xml的作用
配置
*.properties 属性文件
*.xml
数据交换
xml
webservice
json
二、Java中配置文件的三种配置位置及读取方式
1.1 XML和*.properties(属性文件)
1.2 存放位置
1.2.1 src根目录下
Xxx.class.getResourceAsStream("/config.properties");
案例:
InputStream is=Text.class.getResourceAsStream("/db.properties");
Properties pro=new Properties();
try {
pro.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String username=pro.getProperty("username");
String password=pro.getProperty("password");
String realname=pro.getProperty("realname");
System.out.println(username);
System.out.println(password);
System.out.println(realname);
1.2.2 与读取配置文件的类在同一包
Xxx.class.getResourceAsStream("config2.properties");
案例:
InputStream is=Text1.class.getResourceAsStream("db.properties");
Properties pro=new Properties();
try {
pro.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String username=pro.getProperty("username");
String password=pro.getProperty("password");
String realname=pro.getProperty("realname");
System.out.println(username);
System.out.println(password);
System.out.println(realname);
1.2.3 WEB-INF(或其子目录下)
ServletContext application = this.getServletContext();
InputStream is = application.getResourceAsStream("/WEB-INF/config3.properties");
案例:
ServletContext application = this.getServletContext();
InputStream is = application.getResourceAsStream("/WEB-INF/db.properties");
Properties pro=new Properties();
try {
pro.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String username=pro.getProperty("username");
String password=pro.getProperty("password");
String realname=pro.getProperty("realname");
System.out.println(username);
System.out.println(password);
System.out.println(realname);
1.3注意:
*.properties文件
key=value
#注释
Properties.load(is)
三、dom4j+xpath解析xml文件
dom4j:Java开源的项目
DOM由节点组成
Node
元素节点
属性节点
文本节点
document.selectNodes(xpath);//查一组
document.selectSingleNode(xpath);//查单个
xpath等同数据库的select语句
xpath
/ 路径 在系统中建一个文件叫document/students/student/sid|name
@ 属性
案例一:
InputStream is=Test.class.getResourceAsStream("/students.xml");
SAXReader saxReader = new SAXReader();
Document document=null;
try {
document= saxReader.read(is);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String xpath="/students/student";
List <Element> studentNodes= document.selectNodes(xpath);
for (Element studentNode : studentNodes) {
// Attribute attribute = studentNode.attribute("sid");
// String sid=attribute.getText();
String sid=studentNode.attributeValue("sid");
Element nameNode=(Element) studentNode.selectSingleNode("name");
String name=nameNode.getText();
System.out.println(sid+","+name);
}
案例二:
InputStream is=Test1.class.getResourceAsStream("/students.xml");
SAXReader saxReader = new SAXReader();
Document document=null;
try {
document= saxReader.read(is);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String xpath="/students/student[@sid='s002']/name";
Element nameNode = (Element) document.selectSingleNode(xpath);
String name=nameNode.getText();
System.out.println(name);
四:xml建模
思路:把xml中的元素变成实体类,元素的属性变成实体类中的属性,封装该类,再定义一个Map集合装对象,再加上一个放置对象和取出对象的方法,最后写一个工厂类来生产该对象,得到你想要的对象的信息。
案例:
config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action
path CDATA #REQUIRED
type CDATA #REQUIRED
>
<!ATTLIST forward
name CDATA #REQUIRED
path CDATA #REQUIRED
redirect (true|false) "false"
>
]>
<!-- config标签:可以包含0~N个action标签 -->
<config>
<!-- action标签:可以饱含0~N个forward标签 path:以/开头的字符串,并且值必须唯一 非空 type:字符串,非空 -->
<action path="/regAction" type="test.RegAction">
<!-- forward标签:没有子标签; name:字符串,同一action标签下的forward标签name值不能相同 ; path:以/开头的字符串
redirect:只能是false|true,允许空,默认值为false -->
<forward name="failed" path="/reg.jsp" redirect="false" />
<forward name="success" path="/login.jsp" redirect="true" />
</action>
<action path="/loginAction" type="test.LoginAction">
<forward name="failed" path="/login.jsp" redirect="false" />
<forward name="success" path="/main.jsp" redirect="true" />
</action>
</config>
ForwardModel类:
/**
* xml文件中forward元素实体类
* @author Administrator
*2018年5月8日下午3:25:01
*/
public class ForwardModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String path;
private boolean redirect;
public ForwardModel() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
public void setRedirect(String redirect) {
this.redirect = Boolean.parseBoolean(redirect);
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "ForwardModel [name=" + name + ", path=" + path + ", redirect=" + redirect + "]";
}
}
ActionModel类:
/**
* xml文件中action元素实体类
* @author Administrator
*2018年5月8日下午3:25:01
*/
public class ActionModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String path;
private String type;
private Map<String, ForwardModel> ForwardModels=new HashMap<String, ForwardModel>();
//添加一个ForwardModel对象
public void put(ForwardModel forward) {
//校验代码
ForwardModels.put(forward.getName(), forward);
}
//取出ForwardModel对象
public ForwardModel get(String name) {
return ForwardModels.get(name);
}
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;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "ActionModel [path=" + path + ", type=" + type + ", ForwardModels=" + ForwardModels + "]";
}
}
ConfigModel类:
/**
* xml文件中config元素实体类
* @author Administrator
*2018年5月8日下午3:25:01
*/
public class ConfigModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
//定义一个装ActionModel对象的Map集合
private Map<String, ActionModel> actionModels=new HashMap<String, ActionModel>();
//添加一个ActionModel对象
public void put(ActionModel actionModel) {
//校验代码
String path=actionModel.getPath();
//正则
String regex="^/.+$";
Pattern pattern = Pattern.compile(regex);
//匹配
Matcher matcher = pattern.matcher(path);
boolean f=matcher.matches();
if(!f) {
throw new RuntimeException("path["+path+"]必须以/开头");
}else if(actionModels.containsKey(path)) {
throw new RuntimeException("path["+path+"]必须唯一");
}
actionModels.put(actionModel.getPath(), actionModel);
}
//取出ActionModel对象
public ActionModel get(String path) {
return actionModels.get(path);
}
}
ConfigModelFactory类:
/**
*
* @author Administrator
*2018年5月8日下午3:42:13
*/
public class ConfigModelFactory {
//1私有化ConfigModel对象
private static ConfigModel configModel;
private ConfigModelFactory() {
}
//2公开一个创建ConfigModel对象代理方法
public static ConfigModel createConfigModel(String filepath) {
if(configModel==null) {
configModel=new ConfigModel();
init(filepath);
}
return configModel;
}
//3初始化
private static void init(String filepath) {
try {
//定义
String path=null;
String type=null;
List<Element> forwardElementList = null;
String name = null;
String forwardpath = null;
String redirect = null;
//获得读流
InputStream is=ConfigModelFactory.class.getResourceAsStream(filepath);
//读取xml
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(is);
//得到actionElement元素节点
String xpath="/config/action";
List<Element> actionElementList = document.selectNodes(xpath);
for (Element actionElement : actionElementList) {
//得到actionElement元素节点下的path属性
path=actionElement.attributeValue("path");
//得到actionElement元素节点下的type属性
type=actionElement.attributeValue("type");
//创建actionModel对象
ActionModel actionModel = new ActionModel();
actionModel.setPath(path);
actionModel.setType(type);
//往configModel里添加一个ActionModel对象
configModel.put(actionModel);
//得到forwardElement元素节点
forwardElementList = actionElement.selectNodes("forward");
for (Element forwardElement : forwardElementList) {
//得到forwardElement元素节点下的name属性
name = forwardElement.attributeValue("name");
//得到forwardElement元素节点下的path属性
forwardpath = forwardElement.attributeValue("path");
//得到forwardElement元素节点下的redirect属性
redirect = forwardElement.attributeValue("redirect");
//创建forwardModel对象
ForwardModel forwardModel = new ForwardModel();
forwardModel.setName(name);
forwardModel.setPath(forwardpath);
forwardModel.setRedirect(redirect);
//往actionModel里添加一个forwardModel对象
actionModel.put(forwardModel);
}
}
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
ConfigModel configModel = ConfigModelFactory.createConfigModel("/config.xml");
ActionModel actionModel = configModel.get("/loginAction");
ForwardModel forwardModel = actionModel.get("success");
System.out.println(forwardModel.getPath());
}
}