Java operation XML

Source: Internet
Author: User

I have been working on an efficient platform framework recently. In fact, I realized that when I want to build a simple framework, after I have completed what I think is the first version of the interface, at first, I thought I was doing a configurable homepage display. However, after just two weeks, I found that this was not the case, the requirement is unclear, but the two weeks have not been wasted and I have learned a lot. The following describes how to read XML.

When I was working on the system, I often encountered the need to read xml. At the beginning, I started querying and reading through the Internet, then querying and deleting, and then querying and modifying, when I checked the code almost, I found that it would be better if I didn't encapsulate all these operations into a class and called them directly during use, I felt like my head was pretty funny, I checked so much, and I made debugging one by one, so I continued to check the Internet with this mentality (because I really feel that there is definitely something online, if I encapsulate it myself, my head will actually get into the water ).

Source code display:

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. extends entexception; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. SAXReader; import org. dom4j. io. XMLWriter; public class testAddDel EteXML {private Document document; private String filePath; // actual physical path of the file // private WriteLog writelog; public static void main (String [] args) throws disable entexception {// 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. p Rintln (str); // Element root = document. getRootElement (); // get the root node name} public testAddDeleteXML (String filepath=%this.doc ument = null; this. filePath = filepath; // writelog = new WriteLog ();}/*** create XML file * @ param rootName: root node name */public void createXMLFile (String rootName) {if (! FileExist () {this.doc ument = incluenthelper. createDocument (); this.doc ument. addElement (rootName); saveXMLFile(this.doc ument) ;}}/*** get an existing XML Document * @ return */public Document getXmlFile () {if (fileExist ()) {SAXReader reader = new SAXReader (); try {this.doc ument = reader. read (new File (filePath);} catch (incluentexception 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.doc ument;}/*** add element * @ param fatherPath: parent node name * @ param fatherattr: parent node attribute * @ param childName: name of the node to be added * @ param childValue: value of the node 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 element * @ param fatherPath: parent node name * @ param fatherattr: parent node attribute * @ param childName: name of the node to be modified * @ param childValue: 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 attribute * @ param childName: name of the node to be deleted */publi C 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 attribute * @ param childName: 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 * @ p Aram fatherPath: parent node name * @ param fatherattr: parent node attribute * @ param childName: 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 attribute * @ param childName: name of the node to be deleted */public String getChild (String fatherNode, String fath ErAttr, String childName) {String result = ""; result = ChildOperator (fatherNode, fatherAttr, childName, "", "get", null, 0); return result ;} /*** subnode operation ** @ param fatherNode: parent node name * @ param fatherAttr: parent node attribute * @ param childName: node to be modified * @ param childValue: modified node value * @ param operator: name of the operation to be executed */private synchronized String ChildOperator (String fatherNode, String fatherAttr, String childName, String childValue, String op Erator, Map mapAttr, int updateId) {String result = ""; if (this.doc ument = null) {return "null" ;}element root = this.doc ument. getRootElement (); // get the root node name if (! Root. getName (). equals (fatherNode) {// If result = XmlElementOperator (root, fatherNode, fatherAttr, childName, childValue, operator, mapAttr) is not added to the root node );} else {if (operator. equals ("add") {Element childelement = root. addElement (childName); // The root node does not have the element attribute value childelement. setAttributeValue ("id", childValue); saveXMLFile(this.doc ument);} else if (operator. equals ("update") {List childelements = root. elements (childna m E); // 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.doc ument);} else if (operator. equals ("delete") {List childelements = Root. elements (childName); // obtain all the child nodes under the current node and determine its value to modify 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.doc ument);} else if (operat Or. equals ("get") {List childelements = root. elements (childName); // obtain all the child nodes under the current node and determine its value to modify for (Iterator childs = childelements. iterator (); childs. hasNext ();) {Element everyone = (Element) childs. next (); result = everyone. getText ();} saveXMLFile(this.doc ument);} else if (operator. equals ("deleteOne") {List childelements = root. elements (childName); // obtain all the child nodes under the current node and determine its value to modify for (Iterator childs = childele Ments. iterator (); childs. hasNext ();) {Element everyone = (Element) childs. next (); String divElement = everyone. attributeValue ("id"); if (divElement. equals (childValue) {root. remove (everyone) ;}} saveXMLFile(this.doc ument);} else if (operator. equals ("deleteAll") {List childelements = root. elements (); // obtain all the child nodes under the current node and determine the value to modify for (Iterator childs = childelements. iterator (); childs. hasNext ();) {Element ev Eryone = (Element) childs. next (); List childeDiv = everyone. elements (); for (Iterator childsDiv = childeDiv. iterator (); childsDiv. hasNext ();) {Element everyoneDiv = (Element) childsDiv. next (); everyone. remove (everyoneDiv) ;}}} saveXMLFile(this.doc ument);} return result;}/*** recursive element operation ** @ param element: element to be recursive * @ param fatherNode: parent node name * @ param fatherAttr: parent node attribute * @ param childName: node to be operated * @ param childValue: Operation Value of the node * @ param operator: name of the operation to be executed */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) {// when the current element is not the parent element we are looking for, continue to look for XmlElementOperator (currentelement, fatherNode, fatherAttr, childName, childValue, operator, mapAttr ); // recursive call} else {if (currentelement. attributeCount ()> 0) {// when the current element has a property value, for (Iterator list = currentelement. attributeIterator (); list. hasNext ();) {// traverses the Attribute Value Attribute attr = (Attribute) list. next (); // obtain the first element if (attr. getValue (). equals (father Attr) {// determines the unique parent element if (operator. equals ("add") {// add Element childelement = currentelement. addElement (childName); // Add a child element to the current element. 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. set AttributeValue ("id", "m1"); // childelement. setAttributeValue ("name", "module1"); // childelement. setAttributeValue ("url", "index1.jsp");} else if (operator. equals ("update") {// modify an element List childelements = currentelement. elements (childName); // obtain all the child nodes under the current node and determine its value to modify 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 (); // obtain all the child nodes under the current node and determine the value 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); // obtain all the child nodes under the current node, determine its value, and modify (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.doc ument); return result ;}/ *** Save the 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) ;}/ *** determines 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:

 

Resolution: The recursive method is used to determine whether to perform operations on nodes or subnodes. Here, if is used to determine which operation is selected, if there are many changes, I feel that dependency injection can be used to save the trouble of if judgment. However, at that time, I only made a demo with no more optimizations, if you are interested, try it.

Conclusion: Reading XML is not difficult. in the. NET system, I wrote about xml reading. However, at that time, I was actually writing one by one. What method should I write? Not only should I write a lot of repeated code, there are also some problems that need to be modified repeatedly. Therefore, sometimes, although the implementation of requirements is important, how to implement them is 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.