C # read/write XML file tool class-meeting all requirements

Source: Internet
Author: User
Tags fsm

It is still necessary to parse the xml configuration table because of work needs. Although XML is very simple, XML is completely blank, so we can only start from scratch and start from Google, for more information, see section ① ② At the end of the article. However, the results are scattered and messy, and the functions are incomplete. The examples cannot be tools. Therefore, I have been trying to find an implementation that can basically meet all the requirements. Probably familiar with the XML structure (it took a long time, although relatively simple, but it takes a little time to digest the concepts such as node, element, and attribute in C # API) the APIs of C # xmldocument and C # xmldocument feel that it is difficult or intuitive to implement some functions through APIS. For example, I want to find all the nodes that contain the attribute "Lang, I thought about how to traverse it, so I was too late to start it. I was surprised to read the article 4. I was surprised to hear that there was still this thing (XPath), and I suddenly felt that I wanted to implement the functions I wanted. Then go to W3C
School XPath specifications.

After thinking about it, I can't help thinking about it. The first idea was to define a stringbuilder XPath variable and then add the relevant operation's XPath string to the back, but I still feel that there are too many situations, function naming becomes a problem (I remember naming it to addnode9 (). I always feel that it is a process of character matching, but there is no "Regular Expression" intelligence, then I think of the confusion that I have always been confused-it is very passive to solve many problems combined with different situations, and I feel confused. There is only a thorough solution. In fact, this is the principle of "regular expression"-finite state machine. Fortunately, I have read the theory of "Finite State Machine" before.

I got up at three in the morning (ah, it's always quite a conflict). I found the FSM code on the codeproject (a lot of it) and downloaded a few. I carefully studied the code, in the end, I felt that FSM was really a little useful. I found that I had never felt "unintelligent". I could use the constraints to avoid it. So I should return to XPath, then there will be the following code (a few tests are normal), and the subsequent sections (directly copy with comments) will not be available (I will go to work later ), then the function is not complete, and you will have time to complete it later (if you want to share it with me, Thank you ).

The following code (assuming you have the foundation of xpath)

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. XML; // code by D. s. qiunamespace xmlparse {class xmlutils {public static stringbuilder XPath = new stringbuilder (); public static xmldocument xmldoc = new xmldocument (); public static xmlelement root = NULL; public static void addcommint (string commit) {XPath. append (COMMIT);} public static void addnode (S Tring name) {XPath. append ("/" + name);} public static void addnoderegardlessposition (string name) {XPath. append ("//" + name);} public static void addnodebyindex (string name, string index) {XPath. append ("/" + name + "[" + index + "]");} public static void addnodebyindexregardlessposition (string name, string index) {XPath. append ("//" + name + "[" + index + "]");} public static void addnodeby Value (string name, string value, string operatorstr = "=") {XPath. append ("[" + name + operatorstr + value + "]");} public static void addindex (string index) {XPath. append ("[" + index + "]");} public static void addattribute (string name) {XPath. append ("[@" + name + "]");} public static void addattributebyvalue (string name, string value, string operatorstr = "=") {XPath. append ("[@" + name + Opera Torstr + value + "]");} public static void addanynode () {XPath. append ("/*");} public static void addanynoderegardlessposition () {XPath. append ("// *");} public static void addanyattribute () {XPath. append ("[@ *]");} public static void load (string filename) {xmldoc. load (filename); root = xmldoc. documentelement;} public static xmlnodelist commit (string commit = NULL) {xmlnodelist xn = NULL; If (Comm It! = NULL) {xn = root. selectnodes (COMMIT);} else if (XPath. length! = 0) {xn = root. selectnodes (xmlutils. XPath. tostring (); XPath. clear ();} return XN;} public void addelement (string path, string node_root, string node_name, string node_text, string att_name, string att_value) {load (PATH ); xmlnodelist nodelist = xmldoc. selectsinglenode (node_root ). childnodes; // obtain all the subnodes of the bookstore node // determine whether a node exists. If a node exists, it traverses all the subnodes to see if there are duplicate nodes, add a new node if (nodelist. count> 0) {foreach (xmlnod E Xn in nodelist) // traverse all subnodes {xmlelement Xe = (xmlelement) xn; // convert the subnode type to xmlelement type if (Xe. getattribute (att_name )! = Att_value) {xmlnode xmldocselect = xmldoc. selectsinglenode (node_root); // select the root node xmlelement son_node = xmldoc. createelement (node_name); // Add the subnode son_node.setattribute (att_name, att_value); // set the attribute son_node.innertext = node_text; // Add the node text xmldocselect. appendchild (son_node); // Add the sub-node xmldoc. save (PATH); // Save the XML file break; }}} else {xmlnode xmldocselect = xmldoc. selectsinglenode (node_root); // select the root node xmlelement son_node = xmldoc. createelement (node_name); // Add the subnode son_node.setattribute (att_name, att_value); // set the attribute son_node.innertext = node_text; // Add the node text xmldocselect. appendchild (son_node); // Add the sub-node xmldoc. save (PATH ); // Save the XML file }}/// <summary> /// modify the content of the node /// </Summary> /// <Param name = "path"> XML file </param> /// <Param name = "node_root"> new content of the root node name </param> /// <Param name = "new_text"> </param> /// <Param name = "att_name"> attribute name of a node </param> /// <Param name = "att_value"> attribute value of a node </Param> Public void updateelement (string path, string node_root, string new_text, string att_name, string att_value) {load (PATH); xmlnodelist nodelist = xmldoc. selectsinglenode (node_root ). childnodes; // obtain all subnodes of the bookstore node foreach (xmlnode Xn in nodelist) // traverse all subnodes {xmlelement Xe = (xmlelement) xn; // convert the subnode type to the xmlelement type if (Xe. getattribute (att_name) = att_value) {Xe. innertext = new_text; // The content value is xmldoc. save (PATH); // Save the break ;}}} /// <summary> /// delete a node /// </Summary> /// <Param name = "path"> physical path of the XML file </param> // /<Param name = "node_root"> root node name </param> // <Param name = "att_name"> attribute name of the node </param> // <Param name = "att_value"> node attribute value </param> Public void deletenode (string path, string node_root, string att_name, string att_value) {load (PATH); xmlnodelist nodelist = xmldoc. selectsinglenode (node_root ). childnodes; xmlnode root = xmldoc. selectsinglenode (node_root); foreach (xmlnode Xn in nodelist) {xmlelement Xe = (xmlelement) xn; If (Xe. getattribute (att_name) = att_value) {// Xe. removeattribute ("name"); // delete the name attribute Xe. removeall (); // delete all contents of the node root. removechild (xe); xmldoc. save (PATH); // Save the break ;}}}}}

Finally, let's talk about my feelings: Because I just graduated, I have never been touched by many problems in my work. Although they are very simple, it will take some time to come out, so d. s. qiu thinks that learning a new thing must be completely understood before it can get twice the result with half the effort. It also records some problems encountered during the learning process and some methods and experiences for solving the problems.

If you. s. qiu has any suggestions or comments that can be commented after the article, or sent an email (gd.s.qiu@gmail.com) Exchange, your encouragement and support is the motivation for me to move forward, hope to have more and better sharing.

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.