Dom4j使用

来源:互联网 发布:js在线客服插件 编辑:程序博客网 时间:2024/06/04 19:37

Dom4j相关操作

只要不是最末端标签,都可以做

1)Element element(String Qname)获取某一层标签下的名为  Qname的标签

   这获得是就是一层标签,不是一个标签范围;通过这一层标签可以获得下一层标签

2)List elements() 获取某一层标签下的所有标签的列表

一.不使用XPath表达式

///////////////////////////添加标签/////////////////////////////

/** * 在固定的位置上添加一个新的标签 * 主要是运用list添加元素的的操作 */public static void addByLocation() throws Exception {//首先的三步SAXReader saxReader = new SAXReader();Document document = saxReader.read("src/xml/xml1.xml");Element root = document.getRootElement();//获取所有一级目录的列表List<Element> allList = root.elements("student");//获取一级目录的第一组Element firstE  = allList.get(0);//获取第一组的所有标签List<Element> list1 = firstE.elements();//创建要插入的标签和属性Element school = DocumentHelper.createElement("school");school.setText("红星");//在list1 中插入list1.add(1,school);//回写XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/xml/xml1.xml"), OutputFormat.createPrettyPrint());xmlWriter.write(document);//把document中的内容写到输出流中xmlWriter.close();}

//////////////////////////////////////////////////////////////

/**       * 在末尾添加一个新标签       */   public static void addOne() throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read("src/xml/xml1.xml");      Element root = document.getRootElement();      List<Element> list = root.elements("student");      Element fe = list.get(0);      Elementsex1 = fe.addElement("sex");      sex1.setText("女");//注意这里是在sex1上添加,不是fe      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/xml/xml1.xml"),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }


///////////////////////////查询标签/////////////////////////////

/**    *显示所有的人的名字    */   public static void showAll() throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read("src/xml/xml1.xml");      Element root = document.getRootElement();      List<Element> list = root.elements("student");      for (Element element : list) {         Element e = element.element("name");         System.out.println(e.getText());      }   }}


/////////////////////////修改标签属性///////////////////////////

/**    *修改一个标签的值    */   public static void modifyBy() throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read("src/xml/xml1.xml");      Element root = document.getRootElement();           List<Element> allList = root.elements("student");      Element firstE = allList.get(0);      Element id = firstE.element("id");      id.setText("10");      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/xml/xml1.xml"),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }


 

/////////////////////////删除标签/////////////////////////////

 

/**    *删除某个属性标签    *和在末尾添加一样,找到父节点,在父节点上remove一个要删除的标签    */   public static void deleteBy() throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read("src/xml/xml1.xml");      Element root = document.getRootElement();      List<Element> allList = root.elements("student");      Element firstE = allList.get(0);//父节点      Elementsex = firstE.element("sex");//要删除的标签      firstE.remove(sex);      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(PATH),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }


/////////////////////////获取标签属性///////////////////////////

比如:

<student ID="0">

    <name>张三</name> 

    <id>10</id> 女

</student> 

要得到ID的值

/**    * 获取给定标签的属性值    */   public  static void getAttribute() throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read(PATH);      Element root = document.getRootElement();      List<Element> allList = root.elements("student");      Element firstE = allList.get(0);      String id = firstE.attributeValue("ID");      System.out.println(id);   }


 

一.使用XPath表达式

常用的六种表达式:

 

/////////////////////////查询标签///////////////////////////

/**

    * 使用XPath表达式简化xml操作

    *       查询

    */

   publicstatic void test1()throws Exception {

      SAXReader saxReader = new SAXReader();

      Document document = saxReader.read(PATH);

      List<Node> list =document.selectNodes("//name");

      for (Node node : list) {

         String name = node.getText();

         System.out.println(name);

        

      }

   }

   publicstatic void test2()throws Exception {

      SAXReader saxReader = new SAXReader();

      Document document = saxReader.read(PATH);

      Node node1 =document.selectSingleNode("//student[@ID='0']/name");

      String name = node1.getText();

      System.out.println(name);

   }

 

小项目:

////////////////////////学生信息增删查///////////////////////////

方法类

public class StudentService {   private static final String PATH = "src/xml/data.xml";    /*    * 添加    */   public void addStu(StudentInfo stu) throws Exception {      String name = stu.getName();      String age = stu.getAge();      String id = stu.getId();      SAXReader saxReader = new SAXReader();      Document document = saxReader.read(PATH);      Element root = document.getRootElement();      Element e = root.addElement("info");      Element e1 = e.addElement("id");      Element e2 = e.addElement("name");      Element e3 = e.addElement("age");      e1.setText(id);      e2.setText(name);      e3.setText(age);      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(PATH),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }    /*    * 删除    */   public void deleteStu(String id) throws Exception {      SAXReader saxReader = new SAXReader();      Document document = saxReader.read(PATH);      List<Node> list = document.selectNodes("//id");      for (Node node : list) {         String idc = node.getText();         if (idc.equals(id)) {            Element fa = node.getParent();            Element fafa = fa.getParent();            fafa.remove(fa);         }      }      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(PATH),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }   /*    * 查询    */   public StudentInfo selectStu(String id ) throws Exception{      SAXReader saxReader = new SAXReader();      Document document = saxReader.read(PATH);      List<Node> list = document.selectNodes("//id");      StudentInfo stu = new StudentInfo();      for (Node node : list) {         String idc = node.getText();         if(idc.equals(id)){            Element fa = node.getParent();            Element name = fa.element("name");            Element age = fa.element("age");            String namec = name.getText();            String agc = age.getText();            stu.setName(namec);            stu.setAge(agc);            stu.setId(idc);         }      }      return stu;   }   /*    * 修改姓名为name的学生的学号为ID    */   public void changeStu(String name,String id) throws Exception{      SAXReader saxReader = new SAXReader();      Document document = saxReader.read(PATH);      List<Node> list = document.selectNodes("//name");      for (Node node : list) {         String namec = node.getText();         if (namec.equals(name)) {            Element fa = node.getParent();            Element idE = fa.element("id");            idE.setText(id);         }      }      XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(PATH),            OutputFormat.createPrettyPrint());      xmlWriter.write(document);      xmlWriter.close();   }}<span style="font-family:宋体;color:#ff0000;"><span style="font-size: 11pt;"><strong> </strong></span></span>

学生信息类:

public class StudentInfo {private String name;private String id;private String age ;public StudentInfo() {super();}public String getName() {return name;}public StudentInfo(String name, String id, String age) {this.name = name;this.id = id;this.age = age;}public void setName(String name) {this.name = name;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}@Overridepublic String toString() {return "Information [name=" + name + ", id=" + id + ", age=" + age+ "]";}}

主函数:

public class Test {/** */public static void main(String[] args) throws Exception {StudentService service = new StudentService();/* * 添加操作 *///StudentInfo stu1 = new StudentInfo("张三","0","20");//StudentInfo stu2 = new StudentInfo("李四","1","21");//StudentInfo stu3 = new StudentInfo("王五","2","22");//service.addStu(stu1);//service.addStu(stu2);//service.addStu(stu3);/* * 删除操作 *///service.deleteStu("0");/* * 查询操作// *///StudentInfo stu = service.selectStu("2");//System.out.println(stu.toString());/* * 修改操作 */service.changeStu("王五", "20");}}

xml文件:

<?xml version="1.0" encoding="UTF-8"?><student>   <info>     <id>1</id>      <name>李四</name>      <age>21</age>   </info>    <info>     <id>20</id>      <name>王五</name>      <age>22</age>   </info> </student>




0 0