Java Operation XML Instance code _java

Source: Internet
Author: User
Tags addchild gettext

I've been working on an efficient platform for a while, and actually realizing that I'm going to make a simple framework when I've done what I think is a version of the interface, start to think I want to do is a configurable home page display, but Chi Chi did for two weeks, probably after the function was realized, just found to do is not this, hey, The demand is not clear kill people ah, but this two weeks has not wasted, also learned a lot of things, the following main introduction to read XML.
When you do a system, you often encounter the need to read XML, the beginning is read, so I started the Internet query read, and then query Delete, and then query changes, when the code to check the same time, I found, I do not put these operations are encapsulated into a class, the use of direct call, it is not better, Feeling before the head all show tease, check so many, also one of the debugging, holding this mentality continue to go on the Internet (because I really feel that there must be on the Internet, if my own encapsulation words head is really water).
Source code display:

Copy Code code 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 resides
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 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 {
Write 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 Properties
* @param childname: The name of the node to add
* @param childvalue: The node value to add
*/
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 Properties
* @param childname: The name of the node to modify
* @param childvalue: The node value to be modified
*/
public void Updatechild (string fathernode, String fatherattr,string childname, String Childvalue,int updatid) {
Childoperator (Fathernode,fatherattr,childname,childvalue, "Update", Null,updatid);
}
/**
* Delete Element
* @param fatherpath: Parent node Name
* @param fatherattr: Parent Node Properties
* @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 Element
* @param fatherpath: Parent node Name
* @param fatherattr: Parent Node Properties
* @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 Properties
* @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 an element value
* @param fatherpath: Parent node Name
* @param fatherattr: Parent Node Properties
* @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 Properties
* @param childname: The node to be modified
* @param childvalue: Modified node value
* @param operator: The name of the action 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 root node name

if (!root.getname (). Equals (Fathernode)) {//If 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 root node does not have an attribute value
Childelement.setattributevalue ("id", childvalue);


Savexmlfile (this.document);
}else if (operator.equals ("Update")) {
List childelements = root.elements (childname);
For (iterator Childs=childelements.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 childelements = root.elements (childname);//Get all the child nodes under the current node to determine their value for modification
For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();
List childelements1 = everyone.elements ("module");
For (iterator Childs1=childelements1.iterator (); Childs1.hasnext ();) {
Element everyone1 = (Element) Childs1.next ();
Everyone.remove (EVERYONE1);
}


}

Savexmlfile (this.document);
}else if (operator.equals ("get")) {
List childelements = root.elements (childname);//Get all the child nodes under the current node to determine their value for modification

For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();

result = Everyone.gettext ();
}
Savexmlfile (this.document);
}else if (operator.equals ("Deleteone")) {

List childelements = root.elements (childname);//Get all the child nodes under the current node to determine their value for modification

For (iterator Childs=childelements.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 childelements = root.elements ()//Get all child nodes under the current node to determine their values to modify

For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();
List Childediv = everyone.elements ();
For (iterator Childsdiv=childediv.iterator (); Childsdiv.hasnext ();) {
Element everyonediv = (Element) Childsdiv.next ();
Everyone.remove (EVERYONEDIV);
}
}
}
Savexmlfile (this.document);

}
return result;
}
/**
* Recursive element operations
* @param element: elements to be recursive
* @param fathernode: Parent node Name
* @param fatherattr: Parent Node Properties
* @param childname: The node to be operated on
* @param childvalue: node value after operation
* @param operator: The name of the action 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)) {//The current element is not the parent element we are looking for, continue to find
Xmlelementoperator (currentelement,fathernode,fatherattr,childname,childvalue,operator,mapattr);//Recursive call
}else{
if (Currentelement.attributecount () >0) {//The current element has an attribute value
For (iterator List=currentelement.attributeiterator (); List.hasnext ();) {//Traverse property value
Attribute attr = (attribute) list.next (); Gets the first element in the property value queue
if (Attr.getvalue (). Equals (fatherattr)) {//Determine the unique parent element based on the property value
if (Operator.equals ("add")) {//Add element
Element childelement = currentelement.addelement (childname); Adds a child element to the current element

Childelement.settext (Childvalue); Set the value of a 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 childelements = currentelement.elements (childname);//Get all the child nodes under the current node to determine their value for modification
For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();
Everyone.settext (Childvalue); Modify the element value
}
}else if (operator.equals ("delete")) {///delete a specified element

List childelements = currentelement.elements ()//Get all child nodes under the current node to determine their values to modify

For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();
Currentelement.remove (Everyone);
}
}else if (operator.equals ("get")) {
List childelements = currentelement.elements (childname);//Get all the child nodes under the current node to determine their value for modification
For (iterator Childs=childelements.iterator (); Childs.hasnext ();) {
Element everyone = (element) Childs.next ();
result = Everyone.gettext ();
Result =everyone.attributevalue ("id") + "," +result;
}
}
else{
Write 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 if an 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:

Copy Code code 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>

Parsing: Here The recursive method is used to determine the operation of the node or child node, relatively clear, here is the use of if judgment to determine the choice is that kind of operation, if relatively more changes, I feel can use dependency injection, eliminating the trouble of if judgment, but at that time just did a demo, No more optimizations, if you are interested you can try.
Summary: Reading XML is not difficult in fact, writing. NET system, I wrote about XML reading, but at that time is really one of the write, what is required in which method to write what, not only to write a lot of duplicate code, and a little problem needs to be repeated changes, so, sometimes, although the realization of the need is important, but how to achieve, equally important!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.