//读取内容
public void read() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element root = document.getRootElement();
Element book = (Element) root.elements("书").get(1);//获取xml中的第二本书
String value = book.element("书名").getText();
}
//读取属性
public void readAttr() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element root = document.getRootElement();
Element book = (Element) root.elements("书").get(1);//获取xml中的第二本书
String value = book.element("书名").attributeValue("name");
}
//添加
public void add() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element book = document.getRootElement().element("书");
book.addElement("售价").setText("209");
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/book.xml"),"utf-8"));
writer.write(document);
writer.close();
}
//向指定位置添加element
public void add2() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element book = document.getRootElement().element("书");
List list = book.elements();
Element element = DocumentHelper.createElement("售价");
element.setText("309");
list.add(2, element);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"), format);
writer.write(document);
writer.close();
}
//删除
public void delete() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element price = document.getRootElement().element("书").element("售价");
price.getParent().remove(price);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"), format);
writer.write(document);
writer.close();
}
//更新
public void update() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
Element book = (Element) document.getRootElement().elements("书").get(1);
book.element("作者").setText("或黎明");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"), format);
writer.write(document);
writer.close();
}
//利用xpath提取xml文档中的数据
public void extract() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
String value = document.selectSingleNode("作者").getText();//得到第一个作者的名字
}
//查找user.xml中是否有 和用户相匹配的用户名和密码
@Test
public void extract2() throws Exception{
String userName = "aaa";
String passWord ="123";
SAXReader reader = new SAXReader();
Document document = reader.read("src/users.xml");
Node node = document.selectSingleNode("//user[@userName=‘"+userName+"‘ and @passWord=‘"+passWord+"‘]");
if(node == null){
System.out.println("登陆失败!");
}else{
System.out.println("登陆成功!");
}
}
dom4j解析 操作xml