. NET creating, adding, deleting, and modifying XML

Source: Internet
Author: User

Objective:

  Recently made a project, program A in a server program B on another server, however, main program a needs to access program B's picture set folder to download to this server, in order to prevent multiple calls to the Web services, Create an XML file in main program A to record whether a picture in the picture set has been downloaded or not, and if the download does not need to be called, the service needs to be invoked without downloading. I am also a small rookie, has not written before the XML file this piece, so the book (C # Advanced Programming 10th edition Christian Nagel) on the Internet to check the data, finally sorted out a set of their own can be used on the operation of the XML read and write notes. In order to learn and share the decision to put on their own blog, and later encounter similar problems can be consolidated, if there are errors written in the hope that readers leave a message to correct, then see my steps to achieve.

Namespaces that need to be referenced:

Usingusing system.xml;

1. Creating an XML file

        Private voidCreatexml (stringXmlpath)//create an XML file for train        {            if(! File.exists (Xmlpath))//determine if an XML file has been created{XmlDocument doc=NewXmlDocument (); Doc. LOADXML ("<?xml version= ' 1.0 ' encoding= ' gb2312 '?>"+"<train>"+"</train>"); Doc.            Save (Xmlpath); }        }

2. Inserting elements

Private voidAddxmlnode (stringBatchId,stringBatchname,stringBatchno,stringXmlpath)//Add nodes (Training batch ID, training batch name, picture number collection, XML path){XmlDocument xmldoc=NewXmlDocument ();//instance an XML fileXmlDoc. Load (Xmlpath);//reading an XML fileXmlNode Train= xmldoc. selectSingleNode ("Train");//Find TrainXmlElement El= xmldoc. CreateElement ("Trainbatch");//Create a TrainbatchEl. SetAttribute ("Name", batchname);//Add PropertyXmlElement Elbatchid= xmldoc. CreateElement ("BatchId");//Create the first subordinate node of a <trainbatch> nodeElbatchid.innertext = BatchId;//Assign ValueEl. AppendChild (Elbatchid);//Append to TrainbatchXmlElement Elbatchname= xmldoc. CreateElement ("Batchname"); Elbatchname.innertext=Batchname; El.            AppendChild (Elbatchname); XmlElement Elbatchno= xmldoc. CreateElement ("Batchno");//Create a second subordinate node of the <trainbatch> nodeElbatchno.innertext = Batchno;//Assign ValueEl. AppendChild (Elbatchno);//Append to Trainbatchtrain.                                           AppendChild (EL); //append all added elements to the root directoryxmldoc.        Save (Xmlpath); }

3. Modify the value of Batchno under the first Trainbatch node

        Private voidUpdatexmlnode (stringBatchId,stringBatchno,stringXmlpath)//Modify the XML file (training batch ID, collection of picture numbers to be modified, XML path){XmlDocument xmldoc=NewXmlDocument (); XmlDoc.            Load (Xmlpath); XmlNodeList Titlenodes= xmldoc. selectSingleNode ("Train"). ChildNodes;//get train next layer of node            foreach(XmlNode nodeinchTitlenodes)//loop all Trainbatch nodes{XmlElement El= (XmlElement) node. childnodes[0];//Gets the first node value                if(el. InnerText = = BatchId)//determines whether the ID of the first trainbatch equals the ID that will be modified{node. childnodes[2]. InnerText = Batchno;//Assigning a value to the third nodeXmlDoc. Save (Xmlpath);//Save (do not forget this step OH)                     Break; }            }        }

4. Get the Batchno value under the first Trainbatch node

Private stringGetxmlnodevalue (stringBatchId,stringXmlpath)//gets whether a training is recorded in the XML{XmlDocument xmldoc=NewXmlDocument ();//instantiating an XML documentXmlDoc. Load (Xmlpath);//load the document that will be opened            stringresult =""; XmlNodeList Titlenodes= xmldoc. selectSingleNode ("Train"). ChildNodes;//get train next layer of node            foreach(XmlNode nodeinchTitlenodes)//loop all the Trainbatch nodes{XmlElement El= (XmlElement) node. childnodes[0];//gets the first node element under Trainbatch                if(el. InnerText = =BatchId) {Result= node. childnodes[2]. Innertext.tostring ();//returns a third node element under Trainbatch                    returnresult; }             }            returnresult; }

5. Delete Trainbatch nodes based on conditions

Private voidDeletexmlnode (stringBatchname,stringXmlpath)//Delete a node element{XmlDocument xmldoc=NewXmlDocument (); XmlDoc.            Load (Xmlpath); XmlNodeList Titlenodes= xmldoc. selectSingleNode ("Train"). ChildNodes;//get train next layer of node            foreach(XmlNode nodeinchtitlenodes) {XmlElement El=(XmlElement) node; if(el. GetAttribute ("Name") = = Batchname)//el. GetAttribute Get Trainbatch Property{el.                                                         RemoveAll (); //deletes the current element and all child elementsxmldoc.                    Save (Xmlpath);  Break; }            }         }

6.XML Escape character

&lt;

<

Less than

&gt;

>

Greater than

&amp;

&

and number

&apos;

Single quotation marks

&quot;

"

Quotes

Finally, share the code part of the calling method:

protected voidPage_Load (Objectsender, EventArgs e) {             if(!page.ispostback) {stringXmlpath = Server.MapPath ("Testxml.xml");//XML Path AddressCreatexml (Xmlpath); //Creating an XML fileAddxmlnode ("1","ASP. NET Training Phase I.","123,134,454,789,454,315,456", Xmlpath);//Insert First NodeAddxmlnode ("2","ASP. NET Training Phase II","0123,0134,0454,0789,0454,0315,0456", Xmlpath);//Insert a second nodeAddxmlnode ("3","ASP. NET Training Phase III","0123,0134,0454,0789,0454,0315,0456", Xmlpath);//inserting a third nodeAddxmlnode ("4","ASP. NET Training phase Fourth","0123,0134,0454,0789,0454,0315,0456", Xmlpath);//inserting a fourth node                stringresult = Getxmlnodevalue ("1", Xmlpath);//Get node valueUpdatexmlnode ("1","0123,0134,0454,0789,0454,0315,0456", Xmlpath);//Modifying node valuesDeletexmlnode ("ASP. NET Training Phase II", Xmlpath);//Delete a node            }        }

. NET creating, adding, deleting, and modifying XML

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.