目录
3.dom4j+xpath解析xml文件 document for java SAX
1.XML作用
1.1配置 (保存数据)
*.xml和*.properties INI yml springboot
1.2数据交互(获取第三方数据)
webservice xml ajax json
2.Java中3种配置位置及读取方式
2.1如何使用Properties读取配置文件
1)*.properties文件以键值对的方式存储数据;
2)使用Properties类读取配置文件;
2.2 配置位置
1)存放于根目录下,/代表获取src根目录的绝对路径
2)存放于同一类的包下,不加/代表同类名包下的相对路径;
3)存放于WEB-INF目录下
ServletContext sc=this.getServletContext();
InputStream is=sc.getResourceAsStream("/WEB-INF/db.properties");
3.dom4j+xpath解析xml文件 document for java SAX
1)xpath类似数据库中的select语句;
2)Document有节点(Node)组成:元素.节点、属性、文本等
3) Node(节点) Element(元素) 区别 getText();
3)selectNodes()获取节点下所有子节点;
4)selectSingleNode()获取单个节点信息;
5) xpath语法:/(定位路径)、@(获取属性)
4.案例(解析student.xml)
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student sid="s001">
<name>小明</name>
</student>
<student sid="s002">
<name>小芳</name>
</student>
<student sid='a003'>
<name>小王</name>
</student>
<student sid='w004' qq="1111">
<name>小王八</name>
</student>
</students>
public static void main(String[] args) {
//获取io流
InputStream is = Demo02.class.getResourceAsStream("/students.xml");
System.out.println(is);
//创建xml文件读取工具类对象 SaxRead
SAXReader sr = new SAXReader();
//读取.xml配置文件,获得document对象
try {
Document doc = sr.read(is);
//List nodes = doc.selectNodes("//*");
// Node node = doc.selectSingleNode("students/student[@qq]");
// Node selectSingleNode = node.selectSingleNode("name");
// System.out.println(selectSingleNode.getText());
List<Node> nodes = doc.selectNodes("//*[starts-with(@sid,'s')]");
for (Node node : nodes) {
Node selectSingleNode = node.selectSingleNode("name");
System.out.println(selectSingleNode.getText());
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}