C # create and read XML documents

Source: Internet
Author: User
Extensible Markup Language (XML) is developed by W3C. As a new markup language used to replace the HTML language, XML has many basic standards. XML is combined with these standards, applicable to scientific computing, electronic publishing, multimedia production, and e-commerce. C #, as a new type of programming language, is an important part of the. NET Framework. It has a deep relationship with XML. This article will discuss the relationship between the two from one aspect. That is, you can use C # To create and read XML documents.

I. software environment for program design and operation in this article:

(1). Microsoft Windows 2000 Server Edition

(2). Net Framework SDK beta 2

II. C # create an XML document:

In this article, we will introduce two methods for creating XML documents using C #. The two methods have their own merits. The first method is more flexible to create and the second method is more convenient to create.

(1). C # The first method to create an XML document:

This method is to build an XML document step by step according to the XML structure. C # construct an XML document through the various types encapsulated in the namespace "system. xml" in the. NET Framework SDK. The following describes the structure of a typical XML document.

(1) first create an empty XML document:

In the namespace "system. xml", there is a class "xmldocument". C # describes XML documents through this class. Below is an XML document created with C.

Xmldoc = new system. xml. xmldocument ();

(2) Add the XML declaration section to the header of the XML document:

Using the "createnode" method in the "xmldocument" class, you can create an XML node of the specified type. There are three methods to call the "createnode" method. The general method used in this article is as follows, the syntax is as follows:

Xmldocument. createnode method (xmlnodetype, String, string)

Then, add this node to the XML document by using the "appendchild" method in the "xmldocument" class, and use C # To add Declaration paragraphs to the XML document to implement the following statements:

Xmlnode = xmldoc. createnode (xmlnodetype. xmldeclaration ,"","");
Xmldoc. appendchild (xmlnode );
 

(3) add an element to the XML document ):

The data content is added through elements. In the "xmldocument" class, two methods are provided: "createelement" and "createtextnode ". The first method is to create an element in XML, and the other method is to specify the text value for the created element. Below is a root element for the XML document created above.

Xmlelem = xmldoc. createelement ("", "root ","");
Xmltext = xmldoc. createtextnode ("root text ");
 
Note: "xmlelem" is the "xmlelement" object created, and "xmltext" is the "xmltext" object.

With the example of creating an XML element, you can create other data based on the different structure of the data in the XML document.

(2). C # source code (no1.cs) of the first method for creating an XML document ):

Using system;
Using system. xml;
Class mainclass
{
Xmldocument xmldoc;
Xmlnode;
Xmlelement xmlelem;
Xmlelement xmlelem2;
Xmltext;
Static void main (string [] ARGs)
{
Mainclass APP = new mainclass ();
}
Public mainclass ()
{
Xmldoc = new xmldocument ();
// Add the Declaration section of XML
Xmlnode = xmldoc. createnode (xmlnodetype. xmldeclaration ,"","");
Xmldoc. appendchild (xmlnode );
// Add a root element
Xmlelem = xmldoc. createelement ("", "root ","");
Xmltext = xmldoc. createtextnode ("root text ");
Xmlelem. appendchild (xmltext );
Xmldoc. appendchild (xmlelem );
// Add another element
Xmlelem2 = xmldoc. createelement ("sampleelement ");
Xmlelem2 = xmldoc. createelement ("", "sampleelement ","");
Xmltext = xmldoc. createtextnode ("the text of the Sample Element ");
Xmlelem2.appendchild (xmltext );
Xmldoc. childnodes. Item (1). appendchild (xmlelem2 );
// Save the created XML document
Try
{
Xmldoc. Save ("C: \ data. xml ");
}
Catch (exception E)
{
// Display the error message
Console. writeline (E. Message );
}
Console. Readline ();
}
}

(3). C # The second method for creating an XML document:

After introducing the first method, I think every reader will feel that using C # To create XML documents is a complicated task, because not only do you need to understand the creation knowledge, we also need to understand the structure of the document, so that the creation process is step by step. The following describes an easy creation method. This method defines the XML document and saves it to the file.

(1). Create an XML document:

This is the same as the first method.

(2) directly add the XML data to be added to the document through the "loadxml" method in the "xmldocument" class. Of course, the XML you add should conform to the XML syntax, otherwise the generated file will have no significance. The code for adding XML is as follows:

Doc. loadxml (
"<Employees>" +
"<No1>" +
"<Name> Ma Jin Hu </Name>" +
"<Zip> 239000 </zip>" +
"<Address> feng Huang street </address>" +
"<City> Chu Zhou City </city>" +
"<State> Anhui </State>" +
"</No1>" +
"<NO2>" +
"<Name> Wang Tian </Name>" +
"<Zip> 239000 </zip>" +
"<Address> Lang Ya street </address>" +
"<City> He Fei city </city>" +
"<State> Anhui </State>" +
"</NO2>" +
"<NO3>" +
"<Name> Zou Wen Biao </Name>" +
"<Zip> 100000 </zip>" +
"<Address> sai di street </address>" +
"<City> Bei Jin City </city>" +
"<State> Bei jin </State>" +
"</NO3>" +
"</Employees> ");

(3). Save the XML file to the file:

The XML document is saved using the "save" method in the "xmldocument" class. The details are as follows:

Doc. Save ("data. xml ");

(4). C # source code of the second method for creating an XML document (no2.cs ):

Using system;
Using system. IO;
Using system. xml;
Public class sample
{
Public static void main ()
{
// Create an xmldocument object
Xmldocument Doc = new xmldocument ();
Doc. loadxml (
"<Employees>" +
"<No1>" +
"<Name> Ma Jin Hu </Name>" +
"<Zip> 239000 </zip>" +
"<Address> feng Huang street </address>" +
"<City> Chu Zhou City </city>" +
"<State> Anhui </State>" +
"</No1>" +
"<NO2>" +
"<Name> Wang Tian </Name>" +
"<Zip> 239000 </zip>" +
"<Address> Lang Ya street </address>" +
"<City> He Fei city </city>" +
"<State> Anhui </State>" +
"</NO2>" +
"<NO3>" +
"<Name> Zou Wen Biao </Name>" +
"<Zip> 100000 </zip>" +
"<Address> sai di street </address>" +
"<City> Bei Jin City </city>" +
"<State> Bei jin </State>" +
"</NO3>" +
"</Employees> ");
// Save this document to the file
Doc. Save ("data. xml ");
}
}

There are actually many ways to create an XML document using C #. Here we just select two typical methods to introduce them. Regardless of the method, C # uses the. NET Framework SDK when creating XML. Therefore, understanding and understanding the content in this class library is very necessary for C # programming. Next we will introduce how to use C # to read data in XML. Through this, you will find that, C # uses this class library to implement this function.

III. C # Read XML files:

This section uses C # To read the XML file created using the second method in this article. After compiling no2.cs, the execution will generate "data. XML "file, where" data. the data structure of the XML file is as follows:

<Employees>
<No1>
<Name> Ma Jin Hu </Name>
<Zip> 239000 </zip>
<Address> feng Huang street </address>
<City> Chu Zhou City </city>
<State> Anhui </State>
</No1>
<NO2>
<Name> Wang Tian </Name>
<Zip> 239000 </zip>
<Address> Lang Ya street </address>
<City> He Fei city </city>
<State> Anhui </State>
</NO2>
<NO3>
<Name> Zou Wen Biao </Name>
<Zip> 100000 </zip>
<Address> sai di street </address>
<City> Bei Jin City </city>
<State> Bei jin </State>
</NO3>
</Employees>

In the following content, we use C # to read the file and use the listview component to display it according to the data structure. Is the running interface after reading this XML:

Figure 01: C # Run interface after reading XML


To read XML data correctly, you must first understand the XML structure. According to the XML file above, we can know that this XML contains three pieces of data. The following describes how to read these three types of data:

(1) load the XML file to form a data stream:

By creating an "xmldocument" object and then using the "LOAD" method, you can load the XML file as follows:

Xmldocument Doc = new xmldocument ();
// Load the specified XML document
Doc. Load ("C: \ data. xml ");
(2) read the XML file and display it:

XML reading is implemented by creating an "xmlnodereader" object. The "xmlnodereader" object is mainly used to read XML node data. Some "xmlnodereader" attributes are used in the program described in this article, such as the "nodetype" attribute, to determine the type of the read get node. "Value" is the value of a node. The following is the implementation code for reading the XML file and displaying it in listview. listview1 is the listview component that has been created:

While (reader. Read ())
{
// Determine the type of the current read Node
Switch (reader. nodetype)
{
Case xmlnodetype. element:
S = reader. Name;
Break;
Case xmlnodetype. Text:
If (S. Equals ("name "))
Myitem = listview1.items. Add (reader. value );
Else
Myitem. subitems. Add (reader. value );
Break;
}
}

IV. C # source code for reading XML files (read. CS ):

After learning about the above content, you can get the complete code to use C # To read the specified XML file, as follows:

Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. xml;
Public class form1: Form
{
Private button button1;
Private listview listview1;
Private system. componentmodel. Container components = NULL;

Public form1 ()
{
// Initialize components in the form
Initializecomponent ();
}
// Clear resources used in the program
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Private void initializecomponent ()
{
Button1 = new button ();
Listview1 = new listview ();
Suspendlayout ();

Button1.anchor = (anchorstyles. Bottom | anchorstyles. Left)
| Anchorstyles. Right );
Button1.location = new point (240,296 );
Button1.name = "button1 ";
Button1.size = new size (112, 37 );
Button1.tabindex = 0;
Button1.text = "reading XML documents ";
Button1.click + = new system. eventhandler (button#click );

Listview1.anchor = (anchorstyles. Top | anchorstyles. Bottom)
| Anchorstyles. Left)
| Anchorstyles. Right );
Listview1.gridlines = true;
Listview1.location = new point (10, 9 );
Listview1.name = "listview1 ";
Listview1.size = new size (623,269 );
Listview1.tabindex = 1;
Listview1.view = view. details;

This. autoscalebasesize = new size (6, 14 );
This. clientsize = new size (608,348 );
This. Controls. Add (listview1 );
This. Controls. Add (button1 );
This. Name = "form1 ";
This. startposition = formstartposition. centerscreen;
This. Text = "use C # To Read XML documents ";
This. resumelayout (false );

}
Static void main ()
{
Application. Run (New form1 ());
}

Private void button#click (Object sender, system. eventargs E)
{
Listviewitem myitem = new listviewitem ();
// Construct the listview component
Listview1.columns. Clear ();
Listview1.items. Clear ();
Listview1.columns. Add ("name", 80, horizontalalignment. Left );
Listview1.columns. Add ("Zip", 80, horizontalalignment. Left );
Listview1.columns. Add ("Address", 80, horizontalalignment. Left );
Listview1.columns. Add ("city", 80, horizontalalignment. Left );
Listview1.columns. Add ("State", 80, horizontalalignment. Left );
Xmlnodereader reader = NULL;

Try
{
String S = "";
Xmldocument Doc = new xmldocument ();
// Load the specified XML document
Doc. Load ("C: \ data. xml ");
// Set the xmlnodereader object to open the XML file
Reader = new xmlnodereader (DOC );
// Read and display the data in the XML file
While (reader. Read ())
{
// Determine the type of the current read Node
Switch (reader. nodetype)
{
Case xmlnodetype. element:
S = reader. Name;
Break;
Case xmlnodetype. Text:
If (S. Equals ("name "))
Myitem = listview1.items. Add (reader. value );
Else
Myitem. subitems. Add (reader. value );
Break;
}
}
}
Finally
{
// Clear open data streams
If (reader! = NULL)
Reader. Close ();
}
}
}

V. Summary:

C # has a deep relationship with XML. This article only reflects the degree of closeness between the two. There are many class libraries that can directly operate XML in the. NET Framework SDK. It is necessary to use C # development and XML-related programs to master the usage of these class libraries.

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.