For XML, I don't know what I have to know, I don't have to pay ink to describe what it is. I want to make XML in the future, XML will be bigger, XML is the scalable markup language, using it, using it, can make one Set your own data format, data is transmitted in this format in the network and then converts data into a user expectation by XSLT, which is easy to solve the problem of incompatible data format. Data transfer for Internet, I think this is XML for our programmer's most attractive place!
Our theme today is not the benefits of XML, but discuss how to use XML in C #. Let's take a look at some basic theory knowledge that uses the program to access XML.
Two models of access:
In the program, there are two models in the program, which is generally two models, namely the DOM (Document Object Model) and stream model, the advantage of using the DOM is that it allows editing and updating XML documents, which can randomly access the data in the document, you can use XPath queries, however, DOM disadvantages are that it requires one-time load of the entire document to memory, which causes resource issues for large documents. The flow model has solved this problem because it uses the access to the XML file to the concept of flow, that is, when there is only current nodes in memory, but it also has its shortcomings, it is read-only, Forward only, you cannot perform backward navigation operations in the document. Although there are thousands of autumn, we can also use both the programs to achieve advantages and disadvantages, huh, this is the topic! We focus on the reading of XML today, then we will discuss a flow model in detail!
Variations in the stream mode:
Flow models each iterate a node in the XML document, suitable for handling larger documents, and the memory space is small. There are two variants in the stream model - "push" model and "pull" model.
Pushing model is often said, SAX is a model-driven model, that is, it triggers an event for each of the projects that use push models, and we must write the handler of these events, this is very It is very troublesome.
The "pull" model is used in .NET, the "pull" model is used to pull out the document portion of interest from the reader when traverse the document. Do not trigger an event, allow us to access the programming Document, this greatly improves flexibility, "pull" models can selectively process nodes in performance, while SAX discovers that a node will notify the client, so that the use of "pull" model can improve the overall efficiency of Application. The "pull" model in .NET is implemented as an XMLReader class, let's take a look at the inheritance structure of this class:
We will talk about the XMLTextReader class in this architecture. This class provides the ability to read the XML file. It can verify that the document is formatted well. If it is not a good format XML document, this class will be in the reading process Throw XMLException exception, you can use some of this class to read, filter, etc., filter, etc., and get the name and value of the node, please keep in mind: XMLTextReader is based on the implementation of the stream model, hits an inappropriate metaphor, XML If the document is like a water source, the gate is flowing out, and it will not return to return. Only the current node in memory, you can read the next node using the Read () method of the XMLTextReader class. Ok, I said so many ways to see an example, and the programming should pay attention to the actual right. Look at the run effect before watching the code!
EXAMPLE1 Press New Traversal Data, Example2, Example3 Press New Receive Node Type, Example4 Filter Document You only get the data content, and Example5 gets the property node, and Example6 is getting a namespace, and Example7 shows the entire XML document, for this, I specialize in writing A class comes to encapsulates the above functions, such as: // ------------------------------------ -------------------------------------------------- -------------
// XmlReader class with general reading operations for XML files, the following is a brief introduction to this class:
//
// attributes:
// listbox: Set this property primarily in order to get the client control to facilitate the content of the read file (here is a listbox control)
// xmlpath: Set this property to get an absolute path for a determined XML file
//
// Basilic Using (important reference):
//System.xml: This namespace is encapsulated with common class for XML, which uses the XMLTextReader class in this class.
// XmlTextReader: This class provides the ability to read the XML file. It can verify that the document is formatted, if not format
// Good XML document, this class will throw Xmlexception exception during the reading, you can use this class
// Some methods read, filter the document nodes, and get the name and value of the node
//
// Bool XMLTextReader.Read (): Read the next node in the stream, call the method again when reading the last node This method returns false
// xmlnodetype XmlTextReader.NodeType: This property returns the type of current node
// xmlnodetype.element element node
// xmlnodetype.enDelement end element node
// XMLNodetype.xmldeclaration document first node
// xmlnodetype.text text node
// Bool XMLTextReader.hasettributes: Does the current node have properties, return true or false
// String XmlTextReader.name: Returns the name of the current node
// String XmlTextReader.Value: Returns the value of the current node
// String XMLTextReader.localName: Returns the local name of the current node
// String XmlTextReader.NameSpaceuri: Returns the namespace of the current node URI
// String XmlTextReader.prefix: Returns the prefix of the current node
// Bool XmlTextReader.movetonextAttribute (): Move to the next property of the current node
/ / -------------------------------------------------------------------------------------------- -------------------------------------------------- -
Namespace XMLReading
{
Using system;
USING SYSTEM.XML;
Using system.windows.forms;
Using system.componentmodel;
///
/// XML file reader
/// summary>
Public Class XmlReader: IDisposable
{
Private string _xmlpath; private const string _ERRMSG = "Error Occurred While Reading"
Private listbox_listbox;
Private XMLTextReader XMLTXTRD;
#REGON XMLReader constructor
Public XMLReader ()
{
THIS._XMLPATH = String.empty;
THIS._LISTBOX = NULL;
THIS.XMLTXTRD = NULL;
}
///
/// constructor
/// summary>
/// XML file absolute path param>
/// list box is used to display XML param>
Public Xmlreader (String _Xmlpath, ListBox _Listbox)
{
THIS._XMLPATH = _XMLPATH;
THIS._LISTBOX = _Listbox;
THIS.XMLTXTRD = NULL;
}
#ndregion
#REGON XMLReader resource release method
///
/// Clean all the resources being used by this object
/// summary>
Public void dispose ()
{
THIS.DISPOSE (TRUE);
Gc.suppressFinalize (this);
}
///
/// Release the instance variable of the object
/// summary>
/// param>
Protected Virtual Void Dispose (BOOL Disposing)
{
IF (! Disposing)
Return;
IF (this.xmltXtrd! = null)
{
THIS.XMLTXTRD.CLOSE ();
THIS.XMLTXTRD = NULL;
}
IF (this._xmlpath! = null)
{
THIS._XMLPATH = NULL;
}
}
#ndregion
#Region XmlReader properties
///
/// Get or set the list box for display XML
/// summary>
Public ListBox Listbox
{
get
{
Return THISTBOX;
}
set
{
THIS._LISTBOX = VALUE;
}
}
///
/// Get or set an absolute path to the XML file
/// summary>
Public String XMLPath
{
get
{
Return this._Xmlpath;
}
set
{
THIS._XMLPATH = VALUE;
}
}
#ndregion
///
// Traverse XML file
/// summary>
Public void Eachxml ()
{
THIS._ListBox.Items.clear ();
this.xmltXtrd = New XMLTextReader (this._xmlpath);
Try
{
While (xmltxtrd.read ()) {
THIS._ListBox.Items.add (this.xmltXtrd.value);
}
}
Catch (XMLException EXP)
{
Throw new xmlexception (_ERRMSG THIS._XMLPATH EXP.TOSTRING ());
}
Finally
{
IF (this.xmltXtrd! = null)
THIS.XMLTXTRD.CLOSE ();
}
}
///
/// read the node type of the XML file
/// summary>
Public void readxmlbyNodeType ()
{
THIS._ListBox.Items.clear ();
this.xmltXtrd = New XMLTextReader (this._xmlpath);
Try
{
While (Xmltxtrd.Read ())
{
THIS._ListBox.Items.add (this.xmltXtrd.NodeType.toString ());
}
}
Catch (XMLException EXP)
{
Throw new xmlexception (_ERRMSG THIS._XMLPATH EXP.TOSTRING ());
}
Finally
{
IF (this.xmltXtrd! = null)
THIS.XMLTXTRD.CLOSE ();
}
}
///
// / Filter XML document according to node type
/// summary>
/// XMLNodType Node type of array param>
Public void filterbyNodetype (XMLNodetyPe [] XMLNTYPE)
{
THIS._ListBox.Items.clear ();
this.xmltXtrd = New XMLTextReader (this._xmlpath);
Try
{
While (Xmltxtrd.Read ())
{
For (int i = 0; i { IF (xmltxtrd.nodetype == xmlntype [i]) { THIS._ListBox.Items.add (XmltXtrd.name "IS TYPE" XmltXtrd.NodeType.toString ()); } } } } Catch (XMLException EXP) { Throw new xmlexception (_ERRMSG THIS.XMLPATH EXP.TOSTRING ()); } Finally { IF (this.xmltXtrd! = null) THIS.XMLTXTRD.CLOSE (); } } /// /// Read all text node values for the XML file /// summary> Public void readxmlTextValue () { THIS._ListBox.Items.clear (); this.xmltXtrd = New XMLTextReader (this._xmlpath); Try { While (Xmltxtrd.Read ()) { IF (xmltxtrd.nodetype == xmlnodetype.text) { THIS._ListBox.Items.add (xmltxtrd.value); } } Catch (XMLException XMLEXP) { Throw new xmlexception (_ERRMSG THIS._XMLPATH XMLEXP.TOSTRING ()); } Finally { IF (this.xmltXtrd! = null) THIS.XMLTXTRD.CLOSE (); } } /// /// Read the properties of the XML file /// summary> Public void readxmlattributes () { THIS._ListBox.Items.clear (); this.xmltXtrd = New XMLTextReader (this._xmlpath); Try { While (Xmltxtrd.Read ()) { IF (xmltxtrd.nodetype == xmlnodetype.emement) { IF (xmltxtrd.hasettributes) { THIS._ListBox.Items.add ("The Element XMLTXTRD.NAME " HAS " XMLTXTRD.ASTRIBUTECUNT " Attributes "); THIS._ListBox.Items.Add ("The Attributes Are:"); While (xmltxtrd.movetonextAtttribute ()) { THIS._ListBox.Items.Add (XmltXtrd.name "=" XMLTXTRD.VALUE); } } Else { THIS._ListBox.Items.Add ("The Element" "HAS NO Attribute"); } THIS._ListBox.Items.Add (""); } } } Catch (XMLException XMLEXP) { Throw new xmlexception (_ERRMSG THIS._XMLPATH XMLEXP.TOSTRING ()); } Finally { IF (this.xmltXtrd! = null) THIS.XMLTXTRD.CLOSE (); } } /// /// read the namespace of the XML file /// summary> Public void readxmlnamespace () { THIS._ListBox.Items.clear (); this.xmltXtrd = New XMLTextReader (this._xmlpath); Try { While (Xmltxtrd.Read ()) { IF (xmltxtrd.nodetype == xmlnodetype.element && xmltxtrd.prefix! = "") { THIS._ListBox.items.add ("The Prefix" Xmltxtrd.prefix "Is Associated with Namespace" XMLTXTRD.NAMESPACEURI); This._listbox.items.add ("The Element with the local name" "is associated with" "the namespace" xmltxtrd.namespaceuri);} IF (xmltxtrd.nodetype == xmlnodetype.eray && xmltxtrd.hasettributes) { While (xmltxtrd.movetonextAtttribute ()) { IF (xmltxtrd.prefix! = "") { THIS._ListBox.items.add ("The Prefix" Xmltxtrd.prefix "Is Associated with Namespace" XMLTXTRD.NAMESPACEURI); This._listbox.items.add ("THETRIBUTE with the local name" XmltXtrd.localname "is associated with the name" xmltxtrd.namespaceuri); } } } } } Catch (XMLException XMLEXP) { Throw new xmlexception (_ERRMSG THIS._XMLPATH XMLEXP.TOSTRING ()); } Finally { IF (this.xmltXtrd! = null) THIS.XMLTXTRD.CLOSE (); } } /// /// Read the entire XML file /// summary> Public void readxml () { String attnder = string.empty; THIS._ListBox.Items.clear (); this.xmltXtrd = New XMLTextReader (this._xmlpath); Try { While (Xmltxtrd.Read ()) { IF (xmltxtrd.nodetype == xmlnodetype.xmldeclaration) This._listbox.items.add (String.Format ("<{0} {1}?>", xmltxtrd.name, xmltXtrd.value); Else IF (Xmltxtrd.NodeType == XMLNodetype.ement) { Attandele = string.format ("<{0}", xmltXtrd.name); IF (xmltxtrd.hasettributes) { While (xmltxtrd.movetonextAtttribute ()) { Attandele = attndele string.format ("{0} = '{1}'", xmltxtrd.name, xmltxtrd.value; } } Attandele = attndele.trim () ">"; THIS._ListBox.Items.Add (attndele); } Else if (xmltxtrd.nodetype == xmlnodetype.endelement) this._listbox.items.add (" {0}>", xmltxtrd.name); Else IF (Xmltxtrd.NodeType == XMLNODETYPE.TEXT) THIS._ListBox.Items.Add (Xmltxtrd.Value); } } Catch (XMLException XMLEXP) { Throw new xmlexception (_ERRMSG THIS._XMLPATH XMLEXP.TOSTRING ()); } Finally { IF (this.xmltXtrd! = null) THIS.XMLTXTRD.CLOSE (); } } } } The form code is as follows: Namespace XMLReading { Using system; Using system.drawing; Using system.collections; Using system.componentmodel; Using system.windows.forms; Using system.data; USING SYSTEM.XML; Public Class Form1: System.Windows.Forms.form { Private system.windows.forms.listbox listbox1; Private system.windows.Forms.Button button1; Private system.windows.Forms.Button Button2; Private system.windows.Forms.Button Button3; Private system.windows.Forms.Button Button4; Private system.windows.Forms.Button Button5; Private system.windows.Forms.Button button; Private system.windows.Forms.Button Button7; Private string xmlpath; Private XmlReader XRead; /// /// The required designer variable. /// summary> Private system.componentmodel.Container Components = NULL; Public Form1 () { InitializationComponent (); } /// /// Clean all the resources being used. /// summary> Protected Override Void Dispose (Bool Disposing) { IF (Disposing) { IF (Components! = NULL) { Components.dispose (); } } Base.dispose (Disposing); } #Region Windows Form Designer Generated Code /// /// Designer supports the required method - do not use the code editor to modify /// This method is content. /// summary> Private vidinitiRizeComponent () { This.listbox1 = new system.windows.forms.listbox (); This.Button1 = new system.windows.Forms.Button (); this.button2 = new system.windows.Forms.Button (); This.Button3 = new system.windows.Forms.Button (); This.button4 = new system.windows.Forms.Button (); This.button5 = new system.windows.Forms.Button (); This.button6 = new system.windows.forms.button (); This.button7 = new system.windows.forms.button (); THIS.SUSPENDLAYOUT (); // // ListBox1 // THISTBOX1.Anchor = ((System.Windows.Forms.Anchorstyles) ((((System.Windows.Forms.Anchorstyles.top | System.Windows.Forms.Anchorstyles.Bottom) | System.windows.Forms.Anchorstyles.Left) | System.windows.Forms.Anchorstyles.right))))))))))))))))))))))) THISTBOX1.ItemHeight = 12; This.listbox1.location = new system.drawing.point (8, 8); this.listbox1.name = "listbox1"; This.listbox1.size = new system.drawing.size (716, 460); this.listbox1.tabindex = 0; // // Button1 // This.Button1.anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)))); This.Button1.Location = new system.drawing.point (8, 488); This.button1.name = "button1"; This.button1.tabindex = 1; This.Button1.text = "example1"; This.Button1.click = new system.eventhandler (this.button1_click); // // Button2 // This.Button2.Anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)); This.Button2.Location = new system.drawing.point (96, 488); This.Button2.name = "button2"; This.button2.tabindex = 2; This.Button2.text = "example2"; This.Button2.click = new system.eventhandler (this.button2_click); // // Button3 // This.Button3.anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.right)); This.Button3.Location = new system.drawing.point (648, 488); This.button3.name = "button3"; this.button3.tabindex = 3; This.Button3.Text = "example7"; This.Button3.click = new system.eventhandler (this.button3_click); // // Button4 // This.Button4.Anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)); This.Button4.Location = new system.drawing.point (184, 488); This.button4.name = "button4"; This.button4.tabindex = 4; This.Button4.Text = "example3"; This.button4.click = new system.eventhandler (this.button4_click); // // Button5 // This.Button5.Anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)); This.button5.location = new system.drawing.point (272, 488); This.button5.name = "button5"; This.button5.tabindex = 5; This.Button5.Text = "example4"; This.button5.click = new system.eventhandler (this.button5_click); // // Button6 // This.Button6.Anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)); This.button6.location = new system.drawing.point (360, 488); This.button6.name = "button6"; This.button6.tabindex = 6; This.button6.text = "example5"; This.Button6.Click = new system.eventhandler (this.button6_click); // // Button7 // This.Button7.anchor = ((System.Windows.Forms.Anchorstyles) ((System.Windows.Forms.Anchorstyles.Bottom | System.Windows.Forms.Anchorstyles.left)); This.button7.location = new system.drawing.point (448, 488); this.button7.name = "button7"; THIS.BUTTON7.TABINDEX = 7; This.Button7.Text = "example6"; This.button7.click = new system.eventhandler (this.button7_click); // // Form1 // THIS.AUTOSCALEBASESIZE = New System.drawing.size (6, 14); THIS.CLIENTSIZE = New System.drawing.size (728, 517); This.Controls.add (this.button7); This.Controls.add (this.button6); This.Controls.add (this.button5); This.Controls.add (this.button4); This.Controls.add (this.button3); This.Controls.add (this.button2); This.Controls.add (this.button1); This.Controls.add (this.listbox1); THIS.NAME = "Form1"; This.Text = "XmlReader"; This.ResumeLayout (false); // // xmlpath // this.xmlpath = "sample.xml"; } #ndregion /// /// The main entry point for the application. /// summary> [Stathread] Static void main () { Application.run (New Form1 ()); } Private void Button1_Click (Object Sender, System.Eventargs E) { xread = new xmlreader (this.xmlpath, this.listbox1); Try { Xread.eachxml (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } Private void button2_click (Object Sender, System.Eventargs E) { Xread = New Xmlreader (this.xmlpath, this.listbox1); try { Xread.readxmlbyNodetyPE (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } Private void button3_click (Object Sender, System.Eventargs E) { XMLNodType [] XmlNType = {XMLNodeType.Element, XMLNodetype.Endelement, XMLNodetype.xmldeclaration}; xread = new xmlreader (this.xmlpath, this.listbox1); Try { xread.filterbyNodetyPE (XMLNTYPE); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } Private void button4_click (Object Sender, System.Eventargs E) { xread = new xmlreader (this.xmlpath, this.listbox1); Try { Xread.ReadxmlTextValue (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } Private void button5_click (Object Sender, System.Eventargs E) { xread = new xmlreader (this.xmlpath, this.listbox1); Try { xread.readxmlattributes (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.Tostring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); Finally { xread.dispose (); } } Private void button6_click (Object Sender, System.Eventargs E) { xread = new xmlreader (this.xmlpath, this.listbox1); Try { xread.readxmlnamespace (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } Private void button7_click (Object Sender, System.Eventargs E) { xread = new xmlreader (this.xmlpath, this.listbox1); Try { Xread.readxml (); } Catch (XMLException XMLEXP) { Messagebox.show (XmLexp.toString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Catch (Exception Exp) { Messagebox.show (Exp.toT7tring (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error); } Finally { xread.dispose (); } } } } The following is an XML file used to test: In the project, create a new XML file named Sample.xml, and then copy the file to the debug directory under the project's bin directory. XML Version = "1.0" encoding = "UTF-8"?> items> details> order> items> details> order> items> details> order> Customers> Invoicees>