First of all, why do you have dom4j?
Because DOM consumes too much memory, sax can only read XML, not add, delete, etc. As a result, dom4j, which is more efficient, can also be used for CRUD operations.
1.dom4j Introduction
- DOM4J is a simple, flexible library of open source code. DOM4J was developed by the people who developed jdom early and then independently. Unlike Jdom, DOM4J uses interfaces and abstract base classes, and although the DOM4J API is relatively complex, it provides greater flexibility than jdom.
- DOM4J is a very good Java XML API with excellent performance, powerful features, and easy to use features. Many of the dom4j used by software now, such as Hibernate, including Sun's own JAXP, also use dom4j.
- With dom4j development, you need to download the dom4j corresponding jar file and import it into the project. dom4j Download
2.dom4j Case
Still using our previous XML file:
<?xml version= "1.0" encoding= "Utf-8" standalone= "no"?>< class > < student address ="Hong Kong"> < name >Zhouxiao</ name > < age >23</ Age > < introduction >Study hard</ Introduction > </ Students > < student address ="Macau"> < name >Xiao Lin</ name > < age >25</ Age > < introduction >is a good student</ Introduction > </ Students ></ class >
The document is placed in the com.dom4j.test
package.
Using dom4j also gets to represent the entire document Document
object, but this is org.dom4j
in the package.
Get the Document object in the main method as follows:
// 1.得到一个解析器new SAXReader();// 2.指定解析哪个XML文件Document document = saxReader.read(new File("src/com/dom4j/test/myClass.xml"));
Then we can write the corresponding method according to the requirement, and call it in the Main method.
"1" specifies reading an element (reading the first Student's information)
Public Static void Read(Document Document) {//Get root elementElement root = Document.getrootelement ();//root.elements ("Student"): Indicates that all student elements under root are removed //Root.element ("Student"): Indicates that the first student element under root is removedElement student = Root.element ("Student");//Take out PropertiesString address = Student.attributevalue ("Address");//Remove the values of each child nodeString name = Student.element ("Name"). GetText (); String age = Student.element ("Age"). GetText (); String intro = student.element ("Introduction"). GetText (); SYSTEM.OUT.PRINTLN (address); SYSTEM.OUT.PRINTLN (name); System.out.println (age); System.out.println (intro);}
"2" add element: Add a student information to an XML document
Public Static void Add(Document Document)throwsException {///We'll start by creating a student node objectElement student = Documenthelper.createelement ("Student"); Element name = Documenthelper.createelement ("Name"); Name.settext ("Xiao Qiang"); Element age = Documenthelper.createelement ("Age"); Age.settext ("a"); Element intro = documenthelper.createelement ("Introduction"); Intro.settext ("It's a Miyoshi students.");//Add three sub-elements to the student nodeStudent.add (name); Student.add (age); Student.add (Intro);//Add attributes to studentsStudent.addattribute ("Address","Dali");//Add student nodes to the root nodeDocument.getrootelement (). Add (student);//update XML file, direct output will appear in Chinese garbled, to use OutputFormatOutputFormat output = Outputformat.createprettyprint ();//Set the output encoding to Utf-8Output.setencoding ("Utf-8");//Here must use FileOutputStream word throttle output, can not use filewriter, otherwise there will be garbledXMLWriter XMLWriter =NewXMLWriter (NewFileOutputStream ("Src/com/dom4j/test/myclass.xml"), output); Xmlwriter.write (document); Xmlwriter.close ();}
Adding students to XML documents also requires that the in-memory document object be written to the appropriate file at the end, otherwise all operations are done in memory and are not exported to the file, which is similar to DOM.
We can still write this updated code in a separate way, as follows:
publicstaticvoidupdatethrows Exception { // 更新xml文件,直接输出会出现中文乱码,要用OutputFormat OutputFormat output = OutputFormat.createPrettyPrint(); // 设置输出的编码为utf-8 output.setEncoding("utf-8"); new XMLWriter(new FileOutputStream("src/com/dom4j/test/myClass.xml"), output); xmlWriter.write(document); xmlWriter.close();}
"3" adds an element to a specified position
publicstaticvoidaddByIndexthrows Exception { // 创建一个元素 Element newStu = DocumentHelper.createElement("学生"); newStu.setText("王小明"); // 得到所有学生的list List allStudent = document.getRootElement().elements("学生"); allStudent.add(1, newStu); update(document);}
This is actually added directly in the Get List
, and then updated. It's List
java.util
in the bag.List
"4" Delete an element or delete the attribute of this element
Deleting an element is similar to the DOM by removing the node from the corresponding parent node. Let's say we want to delete the first Student node:
publicstaticvoiddeletethrows Exception { // 找到该元素 Element student = document.getRootElement().element("学生"); // 删除元素的某个属性 student.remove(student.attribute("地址")); // 通过父节点删除节点 student.getParent().remove(student); update(document);}
"5" Update element
For example, we want to add the age of all students to 1 and change the address attribute of all students to the United States:
publicstaticvoidupdateAgeAndAddressthrows Exception {Element root = document.getRootElement(); List<Element> list = root.elements(); for (Element element : list) { // 更新属性 element.addAttribute("地址""美国"); // 更新年龄子节点的值 Element e_age = element.element("年龄"); int age = Integer.parseInt(e_age.getTextTrim()); 1)); } update(document);}
The dom4j of xml--xml analysis