Recently, I have been working on an efficient platform framework. In fact, when I realized that I wanted to make a simple framework, after I had finished the first-page interface I thought, I began to think that what I wanted to do was a configurable homepage display, but After working hard for two weeks, probably after the function was implemented, I realized that this is not what I want to do. Alas, it is a pity that I don’t know the requirements, but these two weeks have not been wasted, and I have learned a lot from it. The following are the main things Introduction to reading XML.
When building a system, I often encounter the need to read xml. At the beginning, I read it, so I went online to query and read it, then query and delete it, and then query and modify it. When these codes were searched almost the same, I found that , Why don’t I encapsulate all these operations into a class and call them directly when using them? I feel like my mind was so funny before, I checked so many of them and debugged them one by one, with this mentality Continue to check online (because I really feel that there must be something online, if I encapsulate it myself, my head will really get water).
Source code display:
The code copy is as follows:
package com.gxpt.struts2;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class testAddDeleteXML {
private Document document;
private String filePath; //The actual physical path where the file is located
//private WriteLog writelog;
public static void main(String[] args) throws DocumentException {
//String filepath = System.getProperty("user.dir")+"/XmlFiles/LocalServicesConfig.xml";
String filepath ="F://JAVA Project//University Platform//demo//gxpt//WebContent//limits//manager.txt";
testAddDeleteXML operator = new testAddDeleteXML(filepath);
operator.getXmlFile();
//Map map = new HashMap();
//map.put("id", "m1");
//map.put("name","module1");
//map.put("url", "index1.jsp");
//operator.addChild("div", "div9","module", "",map);
//operator.updateChild("style", "", "div", "asdfasdf",1);
operator.deleteChildOne("style", "","div","div11");
//operator.deleteChild("div", "div9","module");
//String str = operator.getChild("div", "div8", "module");
//System.out.println(str);
//Element root = document.getRootElement();//Get the root node name
}
public testAddDeleteXML(String filepath){
this.document = null;
this.filePath = filepath;
//writelog = new WriteLog();
}
/**
* Create XML file
* @param rootName: root node name
*/
public void createXMLFile(String rootName) {
if(!fileExist()){
this.document = DocumentHelper.createDocument();
this.document.addElement(rootName);
saveXMLFile(this.document);
}
}
/**
* Get an existing XML document
* @return
*/
public Document getXmlFile() {
if (fileExist()) {
SAXReader reader = new SAXReader();
try {
this.document = reader.read(new File(filePath));
} catch (DocumentException e) {
// String loginfo = StackTraceToString.getExceptionTrace(e);
// writelog.writeLogToEnd("LocalServerManager", loginfo);
} finally{
reader = null;
}
} else {
//Writing a log
// String loginfo = "XML file does not exist,read error!";
// writelog.writeLogToEnd("LocalServerManager",loginfo);
System.exit(0);
}
return this.document;
}
/**
* Add elements
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The node name to be added
* @param childValue: The node value to be added
*/
public void addChild(String fatherNode, String fatherAttr,String childName, String childValue,Map mapAttr) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"add",mapAttr,0);
}
/**
* Modify elements
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The node name to be modified
* @param childValue: The node value to be modified
*/
public void updateChild(String fatherNode, String fatherAttr,String childName, String childValue,int updateId) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"update", null,updatId);
}
/**
* Delete elements
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The name of the node to be deleted
*/
public void deleteChild(String fatherNode, String fatherAttr,String childName) {
ChildOperator(fatherNode,fatherAttr,childName,"","delete",null,0);
}
/**
* Delete elements
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The name of the node to be deleted
*/
public void deleteChildAll(String fatherNode, String fatherAttr,String childName) {
ChildOperator(fatherNode,fatherAttr,childName,"","deleteAll",null,0);
}
/**
* Delete an element
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The name of the node to be deleted
*/
public void deleteChildOne(String fatherNode, String fatherAttr,String childName,String childValue) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"deleteOne",null,0);
}
/**
* Get the value of an element
* @param fatherPath: parent node name
* @param fatherattr: parent node attribute
* @param childName: The name of the node to be deleted
*/
public String getChild(String fatherNode, String fatherAttr,String childName) {
String result = "";
result = ChildOperator(fatherNode,fatherAttr,childName,"","get",null,0);
return result;
}
/**
* Child node operation
* @param fatherNode: parent node name
* @param fatherAttr: parent node attribute
* @param childName: The node to be modified
* @param childValue: Modified node value
* @param operator: The name of the operation to be performed
*/
private synchronized String ChildOperator(String fatherNode, String fatherAttr,String childName, String childValue,String operator,Map mapAttr,int updateId) {
String result="";
if (this.document == null) {
return "null";
}
Element root = this.document.getRootElement();//Get the root node name
if(!root.getName().equals(fatherNode)){ //If it is not added under the root node
result = XmlElementOperator(root,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);
}else{
if(operator.equals("add")){
Element childelement = root.addElement(childName);//The element attribute value does not exist in the root node
childelement.setAttributeValue("id",childValue);
saveXMLFile(this.document);
}else if(operator.equals("update")){
List children = root.elements(childName);
// for(Iterator children=childlements.iterator();childs.hasNext();){
// Element everyone = (Element)childs.next();
// everyone.setText(childValue); //Modify the element value
// everyone.setAttributeValue("id",childValue);
Element everyone = (Element)childelements.get(updateId);
everyone.setAttributeValue("id",childValue);
// }
saveXMLFile(this.document);
}else if(operator.equals("delete")){
List children = root.elements(childName);//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
List childrenes1 = everyone.elements("module");
for(Iterator children1=childelements1.iterator();childs1.hasNext();){
Element everyone1 = (Element)childs1.next();
everyone.remove(everyone1);
}
}
saveXMLFile(this.document);
}else if(operator.equals("get")){
List children = root.elements(childName);//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
result = everyone.getText();
}
saveXMLFile(this.document);
}else if(operator.equals("deleteOne")){
List children = root.elements(childName);//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
String divElement = everyone.attributeValue("id");
if(divElement.equals(childValue)){
root.remove(everyone);
}
}
saveXMLFile(this.document);
}else if(operator.equals("deleteAll")){
List children = root.elements();//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
List childDiv = everyone.elements();
for(Iterator childrenDiv=childDiv.iterator();childsDiv.hasNext();){
Element everyoneDiv = (Element)childsDiv.next();
everyone.remove(everyoneDiv);
}
}
}
saveXMLFile(this.document);
}
return result;
}
/**
* Recursive element operation
* @param element: The element to be recursive
* @param fatherNode: parent node name
* @param fatherAttr: parent node attribute
* @param childName: The node to be operated on
* @param childValue: node value after operation
* @param operator: The name of the operation to be performed
*/
private synchronized String XmlElementOperator(Element element,String fatherNode,String fatherAttr,String childName,String childValue,String operator,Map mapAttr){
String result = "";
List elements = element.elements();
for(Iterator it=elements.iterator();it.hasNext();){
Element currentelement = (Element)it.next();
If(!currentelement.getName().equals(fatherNode)){ //Continue to search when the current element is not the parent element we are looking for
XmlElementOperator(currentelement,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);//Recursive call
}else{
if(currentelement.attributeCount()>0){ // When the current element has an attribute value, it is
for(Iterator list=currentelement.attributeIterator();list.hasNext();){ //Transf the attribute value
Attribute attr = (Attribute)list.next(); //Get the first element in the attribute value queue
if(attr.getValue().equals(fatherAttr)){//Determine the unique parent element based on the attribute value
if(operator.equals("add")){//Add element
Element childelement = currentelement.addElement(childName); //Add a child element to the current element
childelement.setText(childValue); //Set the value of the child element
Iterator itmapAttr = mapAttr.keySet().iterator();
while(itmapAttr.hasNext()){
String key = (String) itmapAttr.next();
String value = mapAttr.get(key).toString();
childelement.setAttributeValue(key,value);
}
// childelement.setAttributeValue("id", "m1");
// childelement.setAttributeValue("name", "module1");
// childelement.setAttributeValue("url", "index1.jsp");
}else if(operator.equals("update")){//Modify an element
List children = currentelement.elements(childName);//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
Everyone.setText(childValue); //Modify the value of this element
}
}else if(operator.equals("delete")){ //Delete a specified element
List children = currentelement.elements();//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
currentelement.remove(everyone);
}
}else if(operator.equals("get")){
List children = currentelement.elements(childName);//Get all child nodes under the current node, judge their values, and modify them
for(Iterator children=childlements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
//result = everyone.getText();
result =everyone.attributeValue("id")+","+result;
}
}
else{
//Writing a log
// String loginfo = "XmlFile Operator not exists!";
// writelog.writeLogToEnd("LocalServerManager",loginfo);
}
}
}
}
}
}
saveXMLFile(this.document);
return result;
}
/**
* Save XML file
* @param document: XML file name
*/
private void saveXMLFile(Document document) {
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileWriter(new File(filePath)),format);
writer.write(document);
writer.close();
} catch (Exception e) {
// String loginfo = StackTraceToString.getExceptionTrace(e);
// writelog.writeLogToEnd("LocalServerManager", loginfo);
}
}
/**
* Determine whether the XML file exists.
* @param fileName
* @return
*/
private boolean fileExist() {
java.io.File objFile = new java.io.File(this.filePath);
if (objFile.exists()) {
return true;
} else {
return false;
}
}
}
XML file:
The code copy is as follows:
<?xml version="1.0" encoding="utf-8"?>
<style>
<div id="div8">
<module id="m1" name="module1" url="index1.jsp"/>
<module id="m2" name="module2" url="index2.jsp"/>
<module id="m3" name="module3" url="index3.jsp"/>
</div>
<div id="div9">
<module id="m9" name="module9" url="index3.jsp"/>
<module id="m10" name="module10" url="index4.jsp"/>
<module id="m11" name="module11" url="index5.jsp"/>
</div>
</style>
Analysis: Here we use recursive method to determine whether the operation is for the node or child node, which is relatively clear. Here we use if judgment to determine which operation you are choosing. If there are relatively many changes, I feel that you can use dependency injection , saves the trouble of if judgment, but I only made a demo at that time, without more optimizations. If you are interested, you can give it a try.
Summary: It is actually not difficult to read XML. I wrote about XML reading when writing .NET system, but at that time it was really written one by one. What needed to be written in which method is used, not only do I have to write a lot of repetitions There is a problem with the code that needs to be modified repeatedly, so sometimes, although the requirements are important, how to implement them is equally important!