Summary of how XML file reads and writes are implemented

Source: Internet
Author: User

There are two main ways to read and write XML files, one is XmlDocument, the other is Xmltextwriter/xmltextreader.

1,Xmltextwriter/xmltextreader

Read program:

String path= "Myxml.xml";

String str = "";
XmlTextReader xtr = new XmlTextReader (path);

Read () The return value of this method is always true until the return value becomes false until the bottom of the file is reached. In other words, the loop starts at the beginning of the file and reads all the nodes, reading a node at a time until the end of the file is reached:

Try

{
while (XTR. Read ())

At this point, the XTR has information about the current node, which is the node from which the data was just obtained. That is, Xtr.value is the value of the current element, and you can use the IF (str.name== "") to get the value of the element of interest
{
Switch (XTR. NodeType)
{
Case XmlNodeType.Element:
STR + + "Element:" + XTR. Name;
Break
Case XmlNodeType.Text:
STR + + "Text:" + XTR. Value;
Break
Case XmlNodeType.EndElement:
STR + + "EndElement:" + XTR. Name;
Break
Default
Break
}


}
Tb. AppendText (str);

Xtr. Close ();

}

Catch

{

}

When using the NodeType attribute, it is important to understand how the node is connected to the XML unit. For example, look at the following XML elements:

Nanjing

XmlTextReader this element as 3 nodes, in the following order:

1. The label is read as a type XmlNodeType.Element node, and the name "city" of the element can be obtained from the XmlTextReader name property.

2. The text data "Nanjing" is read as a node of type XmlNodeType.Text. The data "Nanjing" can be obtained from the XmlTextReader value property.

3. The label is read as a type xmlnodetype.endelement node. Similarly, the name "city" of an element can be obtained from the XmlTextReader name property.

If XmlTextReader encounters an error, such as a violation of the XML syntax, it throws a System.XML.XMLException type of exception. Code that uses this class should always be protected (in a try ...). Catch block).

Write Program:

XmlTextWriter xtw = new XmlTextWriter (PATH,ASCIIENCODING.ASCII);
Xtw. formatting = formatting.indented;
Xtw. WriteStartDocument ();
Xtw. WriteComment ("It's happy ' s", "the", "the", "file!");
Xtw. WriteStartElement ("grandfather");
Xtw. WriteStartElement ("father");
Xtw. Writename ("Happy");
Xtw. WriteValue ("happy123");
Xtw. WriteElementString ("Me", "NUAA");
Xtw. WriteEndElement ();
Xtw. WriteEndElement ();
Xtw. WriteEndDocument ();
Xtw. Flush ();
Xtw. Close ();
MessageBox.Show ("The XML file was saved successfully.) ");

2, XmlDocument

Write Program:

 try
            {
                 string path = "Happy.xml";
                xmldocument xd = New XmlDocument ();
               
                 XD. Createxmldeclaration ("1.0", "Utf-8", "yes");
                XmlNode root = xd. CreateElement ("Nuaa");
                XmlNode xn = xd. CreateElement ("CAE");
                XmlAttribute xa = Xd. CreateAttribute ("name");

Xa. Value = "Happyhuang";
Root. Attributes.append (XA);
Xn. innertext = "MyTest";
XmlNode XN1 = xd. CreateElement ("CAE1");
XN1. innertext = "MYTEST";

Xn. AppendChild (XN1);

Root. AppendChild (xn);
Xd. AppendChild (root);
Xd. Save (path);
MessageBox.Show ("The file was saved successfully.) ");
}

Catch
{
MessageBox.Show ("File write failed. ");
}

File reads:

In the Write program, XL. selectSingleNode ("CAE") and XL. attributes["Name"]. Value; the CAE and name are only found in NUAA nodes, if they are not found in the child nodes or in child nodes, then the error, that is, it will only be in the NUAA node in the first order of child nodes to find. But the word foreach means traversing all nodes under NUAA, not just the first-order child nodes, so it prints out the innertext of all nodes. Add XL here. selectSingleNode ("CAE") and XL. attributes["Name"]. Value is only tested, if not added, their corresponding node innertext value will also be printed out, now is equivalent to print two times. The main is to find out XL. selectSingleNode ("CAE") and XL. attributes["Name"]. Value this does not error when only the parent of CAE and name are NUAA.

Try

{
String path = "Happy.xml";
String st = "";
XmlDocument xd1 = new XmlDocument ();
Xd1. Load (path);
XmlNodeList XNL = Xd1. SelectNodes ("/nuaa");
foreach (XmlNode xl in XNL)
{
St + XL. InnerText;
XmlNode XL = xl. selectSingleNode ("CAE");

St + XL. InnerText;
St + XL. attributes["Name"]. Value;
}

Tb. AppendText (ST);
}
Catch
{
MessageBox.Show ("file read failed.") ");
}

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.