C # Operations XML additions and deletions change

Source: Internet
Author: User

XML file is a commonly used file format, whether b/S or C/s are everywhere XML figure. XML is a cross-platform, content-dependent technology in an Internet environment, and is a powerful tool for the current processing of structured document information. XML is a simple data storage language that uses a series of simple tags to describe data that can be built in a convenient way, although XML occupies more space than binary data, but XML is extremely simple and easy to master and use. Microsoft also offers a range of class libraries to help us store XML files in our applications.

"Accessing and manipulating XML files in a program generally has two models, namely the use of the DOM (Document Object model) and the flow model, the advantage of using the DOM is that it allows you to edit and update the XML document, you can randomly access the data in the document, you can use the XPath query, but The disadvantage of DOM is that it requires a one-time load of the entire document into memory, which can cause resource problems for large documents. The flow model solves this problem very well because its access to the XML file is based on the concept of flow, that is, at any time in memory only the current node, but it also has its shortcomings, it is read-only, forward-only, not in the document to perform a backward navigation operation. ”

XML File Creation

First look at a simple XML file:

<?xml version= "1.0" encoding= "UTF-8"?><persons> <person  id= "1" >    <name>flyelephant </Name>    <Age>24</Age>  </Person>  <person id= "2" >    <name>keso </Name>    <Age>25</Age>  </Person></Persons>

This is the most common form of Dom XML file, the creation of the word is relatively simple, the code is as follows:

 XmlDocument doc = new XmlDocument (); XmlDeclaration Dec = doc.            Createxmldeclaration ("1.0", "UTF-8", null); Doc.            AppendChild (DEC); root node XmlElement root = Doc.            CreateElement ("Persons"); Doc.            AppendChild (root); The root node of the Add independent child node XmlElement person = doc.            createelement ("person"); Person.            SetAttribute ("id", "1"); Person.            AppendChild (Getchildnode (Doc, "Name", "flyelephant")); Person.            AppendChild (Getchildnode (Doc, "Age", "24")); Root.            AppendChild (person); Add independent child node of the root node person = doc.            createelement ("person"); Person.            SetAttribute ("id", "2"); Person.            AppendChild (Getchildnode (Doc, "Name", "Keso")); Person.            AppendChild (Getchildnode (Doc, "Age", "25")); Root.            AppendChild (person); Doc.            Save ("person.xml"); Console.WriteLine ("Created successfully"); 
the reading of the XML file

There are three ways to read XML in C #, xmldocument,xmltextreader,linq to XML, because I commonly used is XmlDocument method, other methods, interested can try it yourself, see the implementation of the query:

   XmlDocument doc = new XmlDocument ();            Doc. Load ("person.xml");    Load XML file              XmlElement root = Doc. documentelement;   Gets the root node              xmlnodelist personnodes = root. getElementsByTagName ("person"); Gets the person child node collection              foreach (XmlNode node in personnodes)            {                String id = ((XmlElement) node). GetAttribute ("id");   Gets the Name property value of                  string name = ((XmlElement) node). getElementsByTagName ("Name") [0]. InnerText;  Gets the Age child XmlElement collection                  string age = ((XmlElement) node). getElementsByTagName ("Age") [0]. InnerText;                Console.WriteLine ("Number:" + ID + "Name:" + name + "Age:" + ages);            }

  The results are as follows:

XML Additions

XML holds the data results similar to the class, if the business needs to add data to the dynamic inside, this time also need personal control, the code is as follows:

           XmlDocument doc = new XmlDocument ();            Doc. Load ("person.xml");            XmlElement root = Doc. documentelement;            The root node of the Add independent child node              XmlElement person = doc. createelement ("person");            Person. SetAttribute ("id", "3");            Person. AppendChild (Getchildnode (Doc, "Name", "Elephant"));            Person. AppendChild (Doc, "Age", "Getchildnode");            Root. AppendChild (person);            Doc. Save ("person.xml");            Console.WriteLine ("Node added successfully in XML file");

This time the XML file has changed:

<?xml version= "1.0" encoding= "UTF-8"?><persons> <person  id= "1" >    <Name> Flyelephant Modify </Name>    <Age>24</Age>  </Person>  <person id= "2" >    < name>keso</name>    <Age>25</Age>  </Person>  <person id= "3" >    < name>elephant</name>    <Age>23</Age>  </Person></Persons>
XML Modification

To modify one of the nodes, the simplest is to iterate over the elements that you want to modify:

   XmlDocument doc = new XmlDocument ();            Doc. Load ("person.xml");    Load XML file              XmlElement root = Doc. documentelement;   Gets the root node              xmlnodelist personnodes = root. getElementsByTagName ("person"); Gets the person child node collection            foreach (XmlNode node in personnodes)            {                XmlElement ele = (XmlElement) node;                if (ele. GetAttribute ("id") = = "3")                {                    XmlElement Nameele = (XmlElement) ele. getElementsByTagName ("Name") [0];                    Nameele.innertext = nameele.innertext + "modify";                }            }            Console.WriteLine ("Node modification succeeded");            Doc. Save ("person.xml");

Of course, if the XML file is a lot of content, this way is not so reasonable, you can modify a code

            XmlElement Selectele = (XmlElement) root. selectSingleNode ("/persons/person[@id = ' 1 ']");            XmlElement Nameele = (XmlElement) selectele.getelementsbytagname ("Name") [0];            Nameele.innertext = nameele.innertext + "Modify";
XML Delete

After the above operation, the deletion of the node is very simple, the code is as follows:

            XmlDocument doc = new XmlDocument ();            Doc. Load ("person.xml");    Load XML file              XmlElement root = Doc. documentelement;   Gets the root node              xmlnodelist personnodes = root. getElementsByTagName ("person"); Gets the person child node collection              XmlNode Selectnode =root. selectSingleNode ("/persons/person[@id = ' 1 ']");            Root. RemoveChild (Selectnode);            Console.WriteLine ("Node deletion succeeded");            Doc. Save ("person.xml");

The weekend to see the blog is strong, everyone happy weekend ~

C # Operations XML additions and deletions change

Related Article

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.