reading XML using XML guides in C #

Source: Internet
Author: User
Tags bool empty object model resource tostring
XML FOR XML, I guess you all know better, I do not have to use the pen to describe what it is, I think in the future of web development, XML will certainly shine, XML is Extensible Markup Language, the enterprise can develop a set of its own data format, Data is transmitted over the network in this format and then translated into the user's expectations through XSLT, which easily solves the problem of incompatible data formats. Data transfer for the Internet, I think, is the most tempting part of XML for US programmers!

Our topic today is not about the benefits of XML, but about how to use XML in C #. Let's take a look at some of the basics of using programs to access XML.

Two models for access:

Accessing and then manipulating XML files in programs there are generally two models, using the DOM (Document Object model) and the flow model, the advantage of using the DOM is that it allows editing and updating of XML documents, random access to the data in the document, and the use of XPath queries, but The disadvantage of DOM is that it requires a one-time load of the entire document into memory, which can cause resource problems for large documents. The flow model solves the problem very well, because its access to the XML file is based on the concept of a stream, that is, there is only the current node in memory at any time, but it also has its drawbacks, it is read-only, forward only, and cannot perform backward navigation in the document. Although there are advantages and disadvantages, but we can also in the process of both and the implementation of complementary well, oh, this is a digression! We'll talk about XML reading today, so let's discuss the flow model in detail.

Variations in the Flow model:

The flow model iterates one node of an XML document at a time, and is suitable for processing large documents with little memory space. There are two variants of the flow model-the push model and the pull model.

The push model, which is often said to be sax,sax, is an event-driven model, which means that it triggers an event with a push model for every node it finds, and that we have to write the handlers for these events, which is very inflexible and cumbersome.

. NET is based on the "pull" model of the implementation scheme, "pull model pulls the document section of interest out of the reader as it traverses the documentation, does not need to raise events, allows us to programmatically access the document, which greatly increases the flexibility to" pull "the model on performance to selectively handle nodes, Sax notifies clients every node they find, so using the pull model can improve the overall efficiency of the application. The pull model in. NET is implemented as a XmlReader class, and the inheritance structure of the class is shown below:


Let's talk today about the XmlTextReader class in this architecture, which provides the ability to read XML files to verify that the document is well-formed and that if it is not a well-formed XML document, the class throws a XmlException exception in the reading process. You can use some of the methods provided by this class to read a document node. Filtering and so on and get the name and value of the node, please keep in mind: XmlTextReader is based on the implementation of the flow model, playing an inappropriate analogy, the XML file as if the water, brake a boiling water outflow, flowed through the flow will not also not be able to return to the past. There is only the current node at any time in memory, and you can read the next node using the Read () method of the XmlTextReader class. OK, so much to see an example, programming to pay attention to the actual, right. Look at the code before the operation of the effect bar!


Example1 button to traverse the document reading data, Example2,example3 button to get the node type, EXAMPLE4 filter documents only to obtain the data content, Example5 get the attribute node, Example6 button to get the namespace, Example7 display the entire XML document, for this reason, I write a class to encapsulate the above functionality, which is as follows:


//---------------------------------------------------------------------------------------------------
XmlReader class is used for general read operations of XML files, the following is a brief introduction to this class:
//
Attributes (properties):
ListBox: Set this property primarily to get the client control to display the contents of the file read (here is the ListBox control)
Xmlpath: Set this property to get an absolute path to a determined XML file
//
Basilic Using (Important reference):
System.Xml: This namespace encapsulates a common class that operates on Xml, where the XmlTextReader class is used in this class
XmlTextReader: This class provides the ability to read an XML file to verify that the document is well-formed, and if it is not a well-formed//good XML document, the class will throw a XmlException exception during the read process, which can be provided using the
Some methods read and filter the document nodes and get the names and values of the nodes
//
BOOL Xmltextreader.read (): reads the next node in the stream and returns false when the last node is read to call the method again
XmlNodeType Xmltextreader.nodetype: This property returns the type of the current node
XmlNodeType.Element element Node
XmlNodeType.EndElement End Element Node
Xmlnodetype.xmldeclaration The first node of a document
XmlNodeType.Text text node
BOOL Xmltextreader.hasattributes: The current node has no properties, returns 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 URI of the current node
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

public class Xmlreader:idisposable
{
private string _xmlpath;
Private Const string _ERRMSG = "Error occurred while Reading";
Private ListBox _listbox;
Private XmlTextReader xmltxtrd;

Constructors for #region XmlReader

Public XmlReader ()
{
This._xmlpath = string. Empty;
This._listbox = null;
THIS.XMLTXTRD = null;
}


Construction device

xml file absolute path

Public XmlReader (String _xmlpath, ListBox _listbox)
{
This._xmlpath = _xmlpath;
This._listbox = _listbox;
THIS.XMLTXTRD = null;
}

#endregion
Resource release method for #region XmlReader


Clean up all the resources that are being used by the object

public void Dispose ()
{
This. Dispose (TRUE);
Gc. SuppressFinalize (this);
}


Release instance variables for this object

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;
}
}

#endregion
Properties for #region XmlReader


Gets or sets the list box to display the XML

Public ListBox ListBox
{
Get
{
return this._listbox;
}
Set
{
This._listbox = value;
}
}


Gets or sets the absolute path of an XML file

public string Xmlpath
{
Get
{
return this._xmlpath;
}
Set
{
This._xmlpath = value;
}
}

#endregion


Traversing an XML file

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

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 documents based on node type

An array of xmlnodetype node types

public void Filterbynodetype (xmlnodetype[] xmlntype)
{
This._listbox.items.clear ();
THIS.XMLTXTRD = new XmlTextReader (This._xmlpath);
Try
{
while (Xmltxtrd.read ())
{
for (int i = 0; I xmlntype.length 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 XML files

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 ();
}
}


Reading the attributes of an XML file

public void Readxmlattributes ()
{
This._listbox.items.clear ();
THIS.XMLTXTRD = new XmlTextReader (This._xmlpath);

Try
{
while (Xmltxtrd.read ())
{
if (Xmltxtrd.nodetype = = XmlNodeType.Element)
{
if (xmltxtrd.hasattributes)
{
This._listbox.items.add ("The Element" + Xmltxtrd.name + "has" + Xmltxtrd.attributecount + "Attributes");

This._listbox.items.add ("The Attributes are:");

while (Xmltxtrd.movetonextattribute ())
{
This._listbox.items.add (xmltxtrd.name + "=" + Xmltxtrd.value);
}
}
Else
{
This._listbox.items.add ("The Element" + Xmltxtrd.name + "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 ();
}
}


Reading the namespace of an XML file

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" + Xmltxtrd.localname + "are associated with" + "the namespace "+ Xmltxtrd.namespaceuri);
}

if (Xmltxtrd.nodetype = = XmlNodeType.Element && xmltxtrd.hasattributes)
{
while (Xmltxtrd.movetonextattribute ())
{
if (Xmltxtrd.prefix!= "")
{
This._listbox.items.add ("The Prefix" + Xmltxtrd.prefix + "is associated with namespace" + Xmltxtrd.namespaceuri);

This._listbox.items.add ("The Attribute with the local name" + Xmltxtrd.localname + "are associated with the namespace" + 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

public void ReadXml ()
{
String Attandele = 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 (" ", Xmltxtrd.name,xmltxtrd.value));
Else if (Xmltxtrd.nodetype = xmlnodetype.element)
{
Attandele = string. Format ("<{0}", Xmltxtrd.name);
if (xmltxtrd.hasattributes)
{
while (Xmltxtrd.movetonextattribute ())
{
at Tandele = Attandele + string. Format ("{0}= ' {1} '", Xmltxtrd.name,xmltxtrd.value);
}
}

Attandele = Attandele.trim () + ">";
This._listbox.items.add (Attandele);
}
else if (Xmltxtrd.nodetype = = xmlnodetype.endelement)
This._listbox.items.add (String. Format (" ", 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 ();
}
}
}
}




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.