Dom4j is a powerful and common tool to parse the xml file.DOM(Document Object Model)
There are two main stream in parsing xml file:DOM and SAX
Let me introduce the two parts' advantage and disadvantage:
DOM:(W3C introduced)
1.To parse the xml , DOM should load the whole file to create dom tree.
2.When the file is too large , it's easy to cause the memory leak.
SAX:
1.Load the single node to trigger the event, so SAX covers little memeory
2.SAX is easy to read and unconvenient to modify the xml file.
Using dom4j is simple and clear.Important class: Node,Element,Document,Attribute
How to get the element?
For example:
//Get the SAXReader object
SAXReader reader = new SAXReader();
//Get the document object through SAXReader's read() method
Document document = reader.reade(new File(path));
//When the document object has been get , the RootElement should be get to find other child element
Element rootElement = document.getRootElement();
//In the Element, there is a method call element(),which will help us find the child element
Element childElement = rootElement.element("Student");
//Get the element's text content
String content = childElement.getTextTrim();
...
...//other element could also be get.
How to get the attribute?
//1.get the attribute through the attribute's index
Attribute att1 = element.attribute(0);
//2.get the attribute through the attribute's name
Attribute att2 = element.attribute("attribute's name");
//3.get all the attributes' list
List<Attribute> list = element.attributes();
How to get the attribute's value?
//1.get the attribute's value through attribute
String value = attribute.getValue();
//2.get the attribute's value from element and find the attribute by element
String value2 = element.attributeValue("attribute's name");
How to add the Element?
//1.get the root element through Document
Element rootElement = document.getRootElement();
//2.add the Element
rootElement.addElement("Student").addAttribute("id","001").addElement("name").addText("zhangsan");
//3.and you can preread the xml file which is stored in the memory
String xmlText = document.asXML();
System.out.println("xmlText:"+xmlText);
How to remove the element and attribute?
Firstly, you should always remember , to remove the element,get the parentElement is required.
so ,the format to remove the Element is parentElement.remove(childElement);
//1.get the rootElement
Element rootElement = document.getRootElement();
//2.get the elements of the rootElement
List<Element> list = rootElement.elements();
//3.get the specific element
Element stuElement = list.get(0);
//4.remove the Student element by rootElement
rootElement.remove(stuElement);
//5.to check the stuElement has been removed ,we could use asXML() to tell.
System.out.println(document.asXML());