/*
* 使用xpath实现 获取第一个head下面的age值
//head[@id='1']/age
* 使用selectSingleNode("//head[@id='1']/age")
* 步骤和代码
* 1、得到document
* 2、直接使用selectSingleNode方法实现
* xpath //head[@id='1']/age
* 得到document
* Document document = saxr.read("1.xml");
* 直接使用selectSingleNode方法实现
* Node age =document.selectSingleNode("//head[@id='1']/age");
* 得到age里面的值
* String s = age.getText();
* System.out.println(s);
* 实现简单的学生管理系统
* 使用xml当作数据 存储学生信息
*
* 创建一个xml文件 写一些学生信息
* 增加操作
* 1、创建解析器
* 2、得到document
* 3、获取根节点
* 4、在根节点上面创建标签
* 5、在标签上面依次添加标签
* addElement方法添加
* 6、在标签上面依次添加值
* setText("")
* 7、回写xml
* 删除操作 (根据id输出)
* 3、获取到所有的id
* 使用xpath //id 返回list集合
* 4、遍历list集合
* 5、判断集合里面的id和传递的id是否相同
* 6、如果相同 把id所在的父节点删除
* 查询操作
* 3、获取到所有的id
* 4、返回的是list集合 遍历list集合
* 5、得到每一个id的节点
* 6、id节点的值
* 7、判断id的值和传递的id值是否相同
* 8、如果相同 先获取到id的父节点
* 9、通过父节点获取其他的节点值
* 把这些值封装到一个对象里面 返回对象 方便我们进一步操作
* DOM解析分层 树形结构解析 并把标签和属性封装成对象
* SAX解析 自动执行事件 开始 startElement 碰到文本 characters 结束标签 endElement
* dom4j element(qName)
* 在末尾添加使用addElement setText 标签
* 在特定位置添加
* 获取所有子标签 使用elements()
* 使用list里的add(位置,添加的元素)方法
* 删除使用remove方法 但是通过父节点删除
* attributeValue() 获取属性
* XPath 要导包
* selectNodes 多个节点
* selectSingleNode 一个节点
* //id 所有的id节点 //head[@id='1'] head中id属性为1
*
*
*/
public static void main(String[] args) throws Exception {
Student s = selectStu("1");
System.out.println(s.toString());
}
private static Student selectStu(String id) throws Exception {
SAXReader saxr = new SAXReader();
Document document = saxr.read("1.xml");
Student stu = new Student();
List<Node> list = document.selectNodes("//id");
for (Node node : list) {
String idv = node.getText();
if(idv.equals(id)) {
Element head = node.getParent();
String title = head.element("title").getText();
String age = head.element("age").getText();
stu.setTitle(title);
stu.setAge(age);
}
}
return stu;
}