XmlTextWriter read-write XML file in C # (GO)

Source: Internet
Author: User
Tags closing tag manual writing processing instruction

Turn from http://www.jb51.net/article/35230.htm. NET contains a lot of XML-enabled classes that make programmers use XML programming as simple as understanding XML files. In this article, I'll give you an example of a class that is the XmlTextWriter class

The XmlTextWriter class allows you to write XML to a file. This class contains many methods and properties that make it easier for you to work with XML. To use this class, you must first create a new XmlTextWriter object, and then you can add the XML fragment to the object. This class contains a number of methods for adding various types of XML elements to an XML file, and the following table shows the names and descriptions of these methods:

Method description
WriteStartDocument XML declaration written in version "1.0"
WriteEndDocument to close any open elements or attributes
Close closed Stream
Writedoctype writes out a DOCTYPE declaration with the specified name and optional attributes
WriteStartElement writes the specified start tag
WriteEndElement Close an element
Writefullendelement closes an element and always writes the complete closing tag
WriteElementString writes an element that contains a string value
WriteStartAttribute The starting content of the writing property
WriteEndAttribute Close Last WriteStartAttribute call
WriteRaw Manual writing of original tags
WriteString writing a string
WriteAttributeString a property with the specified value
Writecdata writes out the <! containing the specified text [cdata[...] > Blocks
WriteComment Write a comment that contains the specified text <!--...-->
Writewhitespace write a given blank
WriteProcessingInstruction writes a processing instruction with a space between the name and the text, as follows: <?name text?>

If you are familiar with XML, then you will be able to understand the above methods well. Here we will give an example, in this example, we will first create a document, add some elements, and then close the document. After you add elements, you can also add child elements, attributes, and other content. The following code is an example of creating an XML file named title.

Copy CodeThe code is as follows: using System; Using System.IO; Using System.Xml;      public class Sample {public static void Main () {XmlTextWriter writer = new XmlTextWriter ("Titles.XML", null); Writes the root element writer.      WriteStartElement ("items"); Add the child element writer.      WriteElementString ("title", "Unreal Tournament 2003"); Writer.      WriteElementString ("title", "C&c:renegade"); Writer.      WriteElementString ("title", "Dr. Seuss ' s ABC"); Close the root element and write the end tag writer.      WriteEndElement (); Writes XML to the file and closes XmlTextWriter writer.    Close (); } }

If you compile and execute the above code, you will create the XML file with the following content:

Copy CodeThe code is as follows:<items> <title>unreal tournament 2003</title> <title>C&C:Renegade</title> <title>dr. Seuss ' s abc</title> </items>

The above code creates a XmlTextWriter object called writer. When this object is created, it is associated to a file named Titles.XML. Next, the program creates a root property called items, and the WriteStartElement method creates a start tag for the property. Next, the program calls the WriteElementString method to create three child elements. As you can see from the code above, this method uses the first parameter (title in the program above) as the label for the element, and the second parameter as the value of the element. Once you have added all the elements, you need to close the root element. You can then call the WriteEndElement method to close the recently opened element, in this case the most recently opened element is the root element. When all the data has been written and the root element is closed, you can send the message to your XmlTextWriter. This means that you can call the Close method to close it at this time.

The above code is relatively simple, so let's look at an example that uses more methods in the XmlTextWriter class and is more sophisticated.

Copy Code The code is as follows: using System; Using System.IO; Using System.Xml; public class Sample {  public static void Main ()   {     XmlTextWriter writer = new Xmltex Twriter ("Mymedia.xml", null);     //Use automatic indentation for easy reading      writer. formatting = formatting.indented;     //Writing root elements      writer. WriteStartElement ("items");     //start of an element      writer. WriteStartElement ("item");     //Add an attribute      writer to the previously created element. WriteAttributeString ("rating", "R");     //Add child elements      writer. WriteElementString ("title", "The Matrix");      writer. WriteElementString ("format", "DVD");     //Close Item element      writer. WriteEndElement (); //close element     //Add some spaces between nodes      writer. Writewhitespace ("\ n");    &nBsp Write the second element      writer with the original string. WriteRaw ("<item>" +                       "<title>BloodWake</title>" +                       "<format>xbox </format> "+                       "</item>");     //Use formatted string to write a third element      writer. WriteRaw ("\n  <item>\n" +                       "    <title>unreal tournament 2003</title >\n "+                       "    <format>cd</format>\n "+                       "  </item>\n");     //Close the root element      writer. Writefullendelement ();     //write XML to file and close writer      writer. Close ();  }}

The above code compiles after running to get the Mymedia.xml file, the contents of the file are:

Copy CodeThe code is as follows: <items> <item rating= "R" > <title>the matrix</title> &LT;FORMAT&GT;DVD&LT;/FORMAT&G   T   </item> <item> <title>BloodWake</title> <format>XBox</format> </item> <item> <title>unreal Tournament 2003</title> <format>CD</format> </item> &lt ;/items>

The comments in the above code illustrate how the program's functionality is implemented. One thing to keep in mind is that when invoking a method to begin an operation, you need to invoke the method at the appropriate place in the program to end the operation. For example, if you call startelement, you must call EndElement to close the element, but you can also add a child element between the two calls. Whenever you call the EndElement method, it always turns off the element that was recently opened with the Startelement method (which is similar to how the stack works).

It's easy to use XmlTextWriter, but I suggest you try the code and methods yourself. You will find that this code can be easily integrated into your program. You should also remember that XmlTextWriter is just one of the many XML classes provided by. Net. Like XmlTextWriter, other XML classes are also very easy to use.

2)
I'm using a stupid method, but I can help beginners understand the process of accessing XML nodes.
It is known that an XML file (Bookstore.xml) is as follows:

Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "gb2312"?> <bookstore> <book genre= "Fantasy" isbn= "2-3631-4" > &L   T;title>oberon ' s legacy</title> <author>corets, eva</author> <price>5.95</price> </book> </bookstore>

1. Insert a <book> node into the <bookstore> node:

Copy CodeThe code is as follows: XmlDocument xmldoc=new XmlDocument ();    Xmldoc.load ("Bookstore.xml"); XmlNode Root=xmldoc.selectsinglenode ("bookstore");//Find <bookstore> XmlElement xe1=xmldoc.createelement ("book ");//Create a <book> node xe1. SetAttribute ("Genre", "Li Zhanhong");//Set the node genre property xe1. SetAttribute ("ISBN", "2-3631-4");//Set the node ISBN property
XmlElement xesub1=xmldoc.createelement ("title"); Xesub1. Innertext= "CS from beginner to proficient";//Set Text node Xe1.    AppendChild (XESUB1);//Add to <book> node XmlElement xesub2=xmldoc.createelement ("author"); Xesub2.    Innertext= "Waiting for the Czech Republic"; Xe1.    AppendChild (XESUB2);    XmlElement xesub3=xmldoc.createelement ("price"); Xesub3.    innertext= "58.3"; Xe1. AppendChild (XESUB3);
Root. AppendChild (XE1);//Add to the <bookstore> node Xmldoc.save ("Bookstore.xml");

The result is:

Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "gb2312"?> <bookstore> <book genre= "Fantasy" isbn= "2-3631-4" > &L   T;title>oberon ' s legacy</title> <author>corets, eva</author> <price>5.95</price> </book> <book genre= "Li Zhanhong" isbn= "2-3631-4" > <title>cs from Getting Started to mastering </title> <author> waiting for &lt ;/author> <price>58.3</price> </book> </bookstore>

2. Modify the node: Change the genre value of the node with the genre property value to "Li Zhanhong" to "Update Li Zhanhong", and modify the text of the node's child nodes <author> to "Ya Sheng".

Copy CodeThe code is as follows: XmlNodeList Nodelist=xmldoc.selectsinglenode ("bookstore"). childnodes;//gets all child nodes of the bookstore node foreach (XmlNode xn in nodeList)//traverse all child nodes {XmlElement xe= (XmlElement) xn;//the child node class Type to XmlElement if (XE). GetAttribute ("genre") = = "Li Zhanhong")//if the genre attribute value is "Li Zhanhong" {Xe. SetAttribute ("Genre", "Update Li Zhanhong");//Modify this property to "Update Li Zhanhong"
XmlNodeList Nls=xe.       childnodes;//continue to acquire all child nodes of the XE subnodes foreach (XmlNode xn1 in NLS)//Traversal {XmlElement xe2= (XmlElement) xn1;//conversion type if (Xe2. name== "Author")//If you find {Xe2.     innertext= "Ya sheng";//Modify break;//to find the exit to be able to}} break; }    }
Xmldoc.save ("Bookstore.xml");//save.

The final result is:

Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "gb2312"?> <bookstore> <book genre= "Fantasy" isbn= "2-3631-4" > &L   T;title>oberon ' s legacy</title> <author>corets, eva</author> <price>5.95</price> </book> <book genre= "update Li Zhanhong" isbn= "2-3631-4" > <title>cs from Getting Started to mastering </title> <author&gt ; Asia </author> <price>58.3</price> </book> </bookstore>

3. Delete the 2-3631-4 property of <book genre= "fantasy" isbn= "Genre" > node, delete <book genre= "update Li Zhanhong" isbn= "2-3631-4" > node.

Copy CodeThe code is as follows: XmlNodeList Xnl=xmldoc.selectsinglenode ("bookstore"). ChildNodes;
foreach (XmlNode xn in xnl) {XmlElement xe= (XmlElement) xn; if (XE. GetAttribute ("genre") = = "Fantasy") {XE. RemoveAttribute ("genre");//delete genre Property} else if (XE. GetAttribute ("genre") = = "Update Li Zhanhong") {XE. RemoveAll ();//delete the entire contents of the node}} xmldoc.save ("Bookstore.xml");

The final result is:

Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "gb2312"?> <bookstore> <book isbn= "2-3631-4" > <title>obero   N ' s legacy</title> <author>corets, eva</author> <price>5.95</price> </book> <book> </book> </bookstore>

4. Display all data.

Copy CodeThe code is as follows: XmlNode Xn=xmldoc.selectsinglenode ("bookstore");
XmlNodeList Xnl=xn. ChildNodes;
foreach (XmlNode xnf in xnl) {XmlElement xe= (XmlElement) xnf; Console.WriteLine (XE. GetAttribute ("genre"));//Display the property value Console.WriteLine (XE. GetAttribute ("ISBN"));
XmlNodeList Xnf1=xe.     ChildNodes; foreach (XmlNode xn2 in Xnf1) {Console.WriteLine (xn2. InnerText);//Display child node point text}}
    • C # Implementation of methods to improve XML read and write speed

XmlTextWriter read-write XML file in C # (GO)

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.