C # to create and read XML documents

xiaoxiao2021-03-06  149

The extended marker language XML (Extensible Markup Language) is made by W3C organization. It is used to replace a new type of markup in the HTML language. There are many basic standards inside XML, and XML is based on scientific computing, electronic publishing, multimedia production and e-commerce. C # As a new type of programming, an important part of the .NET framework, his relationship with XML is quite deep. This article explores the relationship between these two from one aspect. That is: How to use C # to create and read an XML document. One. This article is designed and running software environment: (1). Microsoft's window 2000 server version (2) .. Net framework SDK Beta 2. C # Create an XML document: In this article, let's introduce two ways to create an XML document with C #. These two methods have a thousand autumn, the first creation is more flexible, and the second creation is more convenient. (1). C # Creating the first method of the XML document: This method is to build an XML document step by step according to XML. C # Build an XML document to be implemented in the various classes packaged in the namespace "System.xml" in the .NET Framework SDK. Let's introduce it to an XML typical document structure. (1). First, create an empty XML document: There is a class "XMLDocument" in the "System.xml" in the namespace, and C # describes the XML document through this class. Here is to create an XML document with C #. XMLDoc = new system.xml.xmldocument (); (2). Declaration of XML in XML document: Declaration of XML: Using the "CreateNode" method in the "XMLDocument" class, you can create a specified type of XML node, " The Createnode "method has three call methods, which use the general method used herein, the specific syntax is as follows: XMLDocument.createnode method (XMLNodType, String, String) then using the" appendchild "method in the" XMLDocument "class in XML This node is added to the document, and the statement to add a declared paragraph implementation with C # is as follows: XMLNode = Xmldoc.createnode (XMLNodType.xmldeclaration, "," "); xmlDoc.Appendchild (XMLNode); (3). XML Document Add Element (ELEMENT): The addition of data is through elements, providing two methods in the "XmLDocument" class: "CreateElement" and "CreateTextNode". The first method is to create an element in XML, and another method specifies the text value for the elements created. Below is an XML document created above to add an root element.

XmLeleM = Xmldoc.createElement ("Root", ""); XMLText = XMLDoc.createtextNode ("Root Text"); Note: Where "Xmlelem" is created "xmlelement" object, "XmlText" is "XMLText" Objects have an example of creating an XML element, you can create additional data based on different structures in the XML document.

(B) .C # source code to create the first method of XML documents (NO1.cs): using System; using System.Xml; class MainClass {XmlDocument xmldoc; XmlNode xmlnode; XmlElement xmlelem; XmlElement xmlelem2; XmlText xmltext; static void Main (string [] args) {MainClass app = new MainClass ();} public MainClass () {xmldoc = new XmlDocument (); // Add the XML declaration paragraph xmlnode = xmldoc.CreateNode (XmlNodeType.XmlDeclaration, "" , ""); XMLDoc.Appendchild (XMLNode); // Add a root element XMLEM = 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 ("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 Error message console.writeline (E.MESSAGE); Readline ();}} (3) .C # Create a second way to create an XML document: After the first method is introduced, I think every reader feels that using C # creation XML documents is a more annoying. Work, because it is necessary to understand the knowledge of creation, but also understand the structure of the document, the process of creation is a step step. Let's introduce a relatively easy creation method, which is directly defined to the XML document, and then save him to the file. (1). Create an XML document: Like the first method, this is not introduced here.

(2). With the "loadXML" method in the XMLDocument class, add the XML data you want to join directly in the document. Of course, the XML you join should meet the syntax of XML, or there is no meaning in the files that have been generated. Here is the specific code to add XML: doc.loadxml ("" "" " Ma jin hu " " 239000 " "< Address> Feng Huang Street " " CHU Zhou City " " anhui " " " " <"" "< Name> Wang Tian " " 239000 " "

" " He Fei City " " Anhui " " " " " " Zou Wen Biao " 100000 " "
sai Di Street " " bei jin city " " bei jin " " ""); (3 ). Put the saved XML document to the file: Save the XML document is through "XMLDocumen The "Save" method in the T type class is implemented.

Specific as follows: Doc.save ("DATA.XML"); (4). Source Code (NO2.CS) of the second method of the XML document: use system; use system.io; use system.xml Public class sample {public static void main () {// Create an XMLDocument Doc = new xmldocument (); doc.loadxml ("" "" " Ma jin HU < / Name> " " 239000 " "

feng Huang Street " " chu zhou city " " anhui " " "" " wang tian " " 239000 " "
lang ya street " " " " anhui " " " " " " Zou Wen Biao " " 100000 " " Sai Di Street " " bei jin city " " bei jin " " " ") ;

/ / Save this document to Doc.save ("DATA.XML") in the file;} There is a lot of ways to create an XML document with C #, which is only selected for two more typical methods. But no matter that way, C # needs to use the .NET Framework SDK when you create XML. So understand and master the content in this class library is necessary for C # programming. In the following we will introduce the data in XML in the XML in the future, through this, C # is use this class library implementation This feature. Three .C # read XML file: This section will use C # to read the XML file created in this paper, after compiling no2.cs, execute the "DATA.XML" file, "DATA. The data structure of the XML file is as follows: ma jin hu 239000

feng Huang Street chu zhou city anhui wang tian 239000
lang ya street he fei city Anhui Zou Wen Biao 100000
sai di street BEI JIN City bei jin In the following, we read this file with C # and display it according to the data structure in accordance with the ListView component. The picture below is the run interface after reading this XML: Figure 01: C # Read the XML running interface To properly read XML data, first understand the structure of XML.

According to the above XML file, you can know that this XML contains three data. Let's see how to read these three data: (1). Load the XML file, form a data stream: By creating a "xmlDocument" object, then use " Load "method, you can load XML files, as follows: XmLDocument doc = new xmldocument (); // Load the specified XML document Doc.Load (" C: //Data.xml "); (2). Read Take the XML file and display it: Reading XML is implemented by creating a "XMLNodeReader" object, "XMLNodeReader" object is mainly used to read XML node data. Some "XMLNodeReader" properties are used in this document, such as the "NodeType" property, which is used to determine what type of reading node. "Value" is the value of the node.

Below is the implementation code that reads the XML file and displayed in ListView, where ListView1 is already created by listView components: while (Reader.Read ()) {// judges the current read node type 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;}} 4.C # reads the source code code of XML file: After understanding the contents of the above, you can get the full code of the specified XML file with C #, which is as follows: use: 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 () {// Initialization Forms InitializeComponent ();} // Clear Protected Override Void Dispose (Bool Disposing) {if (Disposing) { IF (Components! = null) {components.dispose ();}} Base.Dispose (DISPOSIING); oid 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 = "Read XML Document"; button1.click = New System. EventHandler (Button1_Click); ListView1.Anchor = ((ANCHORSTYLES.TOP | Anchorstyles.Right); listview1.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 = "Read XML document with C #"; this.ResumeLayout (false);} static void main () {Application.Run (New Form1 ());} private void button1_click (Object Sender , System.EventArgs e) {ListViewItem myItem = new ListViewItem (); // Construction listview assembly 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 .L EFT); 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 the data in the XML file and display while (Reader.Read) ()) {// Judgment the current read node type Switch (Reader.NodeType) {case xmlnodetype.element: s = reader.Name; Break; case xmlnodetype.text: if (S.Equals ("name") MyItem = Listview1.items.add (reader.value);

转载请注明原文地址:https://www.9cbs.com/read-127392.html

New Post(0)