XML的解析
-
java中配置文件的三种配置位置及读取方式
1.1 XML和*.properties(属性文件)
注 1:*.properties文件
Key=value
#注释
//util包下的属性文件类
Properties properties=new Properties();
//加载一个properties流
Properties.load(is);
//某一个键的值
Properties.getProperty(“键名”);
代码如下:
//获取同包下的资源文件,将其转化为流对象 InputStream in=PropertiesDemo.class.getResourceAsStream("/db.properties"); //文件解析工具类(Properties) Properties p=new Properties(); //加载资源文件 p.load(in); //得到文件key对应的value值 System.out.println(p.getProperty("uname")); System.out.println(p.getProperty("url"));
结果:
mybatis_ssmjdbc:mysql://localhost:3306/mybatis_ssm
1.2 存放位置
1.2.1 src根目录下
类名:class.getresourceAsStream(“/config.properties”);
1.2.2 与读取配置文件的类在同一包
类名:class.getResourceAsStream(“config2properties.”);
1.2.3 WEB-INF(或其子目录下)
ServletContext sc=this.getServletContext();
InputStreais=sc.getResourceAsStream("/WEB-INF/db.properties");
代码:
ServletContext context=request.getServletContext(); InputStream in=context.getResourceAsStream("/WEB-INF/db.properties"); //专门的工具类 Properties p=new Properties(); p.load(in); System.out.println(p.getProperty("uname")); System.out.println(p.getProperty("url"));
2 dom4j+xpath 解析xml 文件
Xpath 等同于数据库的select语句
document.selectNodes(xpath);//查一组
document.selectSingleNode(xpath);//查单个
代码:
SAXReader sax=new SAXReader(); Document dos=sax.read(new File("D:\\Exxp\\javaEE06\\src\\com\\zking\\config.xml")); //查一组 List os=dos.selectNodes("/config/action"); for(Object o:os) { Element elm=(Element)os; System.out.print(elm.attributeValue("name")); System.out.print(elm.attributeValue("path")); System.out.println(elm.attributeValue("redirect")); } //查询一个 Element et=(Element)dos.selectSingleNode("/config/action"); System.out.println(et.attributeValue("path"));
DOM由节点组成
Node
元素节点
属性节点
文本节点
获取指定的属性节点
InputStream is = XmDemo.class.getResourceAsStream("students.xml"); SAXReader saxx = new SAXReader(); Document docc = saxx.read(is); Element node=(Element) docc.selectSingleNode("students/student[@sid='s002']"); System.out.println(node.asXML());
结果:
小芳
3 dom4J 解析
SAXReader 解析器
Read(XML路径) 得到document对象
getRootElement 获取根节点
Element(节点名称) 获取根节点下的指定节点信息
attributeValue(属性名) 获取属性值
Element(节点名称) 获取节点的Element对象
getText() 获取节点的值
作业
// Xpath解析 能够将xml格式的串当做目录结构来进行查找 ListselectNodes = doc.selectNodes("config.xml"); for(Object o:doc.selectNodes("/config/action")) { Element elm=(Element)o; // 1、获取所有action中的type的值 System.out.println(elm.attributeValue("type")); } // 2、获取第二个action中的type的值 Element node=(Element) doc.selectSingleNode("/config/action[@path='/loginAction']"); System.out.println(node.attributeValue("type"));// // 3、获取第二个action的所有forward的path for(Object o:doc.selectNodes("/config/action/forward")) { Element elm=(Element)o; // System.out.println(elm.attributeValue("path")); } // 4、获取第二个action的第二个forward的path Element nodee=(Element) doc.selectSingleNode("/config/action/forward[@class='sa']"); // System.out.println(nodee.attributeValue("path"));