Reading XML documents in C #

Source: Internet
Author: User

This article will show you how to use C # to access an XML file and read the information in a very simple example. The example itself does not have any practical significance, it simply introduces how to invoke Microsoft's XML standard and how to apply it to reality. Hopefully, you'll be inspired by the first contact with C # or a reader who hasn't tried reading XML files through C #. The purpose of this paper is to exchange and share experiences with more friends.
production Process

1. Run Visual Studio.NET, and create a new Visual C #. NET project, here named ReadXml.
2. In Solution Explorer, rename Form1.cs to FrmAuthor.cs (this option is optional).
3. Change the Name property of Form1 to the Frmauthor,text property to read XML Document,font to verdana,9pt (this is optional).
4. Add four controls to the form: the Lable control (NAME:LBL, Text:author Name:), the ComboBox control (Name:cboauthor, Dropdownstyle:dropdownlist), The RichTextBox control (Name:richtxt, Text: Empty), Button control (name:btnshow, Text:show Author ' s Info). Adjust the position of each control, at which point the user interface resembles the following:
5. When you double-click the form, the IDE automatically switches to the Code editing window and automatically adds the form loading method frmauthor_load. Add the following code within the method:
The above code adds several author names to the ComboBox, and the author's information has a corresponding entry in the XML document.

OK, so far, some of the program initialization work that we have to do is finished.     Let's take a look at the main points of knowledge that this routine will show. Before writing the access code, let's look at the contents of the XML document as follows:

<?xml version= "1.0" encoding= "gb2312"?>     <Author>        <Zhang>            <Intro> omit </intro >         </Zhang>        <Fu>            <Intro> omit </Intro>            </Fu> <Mark> <Intro> Omit </Intro>         </Mark>    

This is a simple XML document, each author corresponds to a piece of information (Intro), a total of three piece of information. What we have to do is to read the author's profile, which is the content of the intro section, through the program, according to the structure of the XML document. OK, let's implement the specific code below.

1. Place the above XML document (named Author.xml) at the root of the project (in fact it can be anywhere, but for ease of administration, it is placed directly under the project root). Then go back to vs.net and add the following code to the header in the FrmAuthor.cs code:
Using System.Xml;
Used to refer to the Microsoft System.Xml namespace.
2. Back to frmauthor.cs[design] page, double-click the show Author's Info button, the IDE automatically adds Btnshow_click event in FrmAuthor.cs. In the Btnshow_click event, fill in the following code:
Try{//declarationstring strauthor = This.cboAuthor.Text.Trim (); String strxmlauthor = ""; string Strinfo; XmlDocument doc = new XmlDocument (); System.Xml.XPath.XPathNavigator nav;//= new System.Xml.XPath.XPathNavigator (); System.Xml.XPath.XPathNodeIterator iterator;//= new System.Xml.XPath.XPathNodeIterator ();//validationif (Strauthor = = "") {throw new ArgumentException ("Author", "You must select a Author name!");} Load XML Documentdoc. Load (".. //.. Author.xml ")//set nav Objectnav = ((System.Xml.XPath.IXPathNavigable) (DOC)). CreateNavigator ();//justificationif (Strauthor = = "Zhang") Strxmlauthor = "Zhang"; else if (Strauthor = "Fu Lou Pai") Strxmlautho r = "Fu"; else if (Strauthor = = "Mark Twain") Strxmlauthor = "Mark";//set node Iteratoriterator = nav. Select ("author/" + strxmlauthor);//move to the desired nodeiterator. MoveNext ();//get the value of current nodestrinfo = iterator. Current.value;//display Author ' s informationthis.richtxt.Text = Strinfo;} catch (System.Exception err) {//display ErrormessagebOx. Show (Err.  Message, "error!");}
3. We have completed the main code. After using the menu build > Build Solution command, press F5 to run the test program correctly.

Explanation section

1. The System.Xml namespace System.Xml namespace provides standards-based support for processing Xml. The supported standards include:
XML 1.0-http://www.w3.org/tr/1998/rec-xml-19980210-Includes DTD support.
XML namespaces-http://www.w3.org/TR/REC-xml-names/-stream levels and DOM.
XSD Schema-Http://www.w3.org/2001/XMLSchema
XPath expression-Http://www.w3.org/TR/xpath
XSLT Transformation-HTTP://WWW.W3.ORG/TR/XSLT
DOM Level 1 Core-http://www.w3.org/TR/REC-DOM-Level-1/
DOM Level 2 Core-http://www.w3.org/TR/DOM-Level-2/
2. The XPathNavigator class XPathNavigator is based on the XPath data model and provides the methods required to implement an XPath query on any data store. XPathNavigator provides read-only random access to data. The current node refers to the node on which the navigator is positioned. Use any Move method to advance the navigator and the property reflects the value of the current node.
3. The XPathNodeIterator class XPathNodeIterator class refers to providing an iterator on a selected set of nodes. The word iteractor is derived from iterate (repeated, reiterated, restated), which iterates over the selected node, and in our case it looks for the node that meets the criteria and obtains the value on that node.

For the System.Xml namespace and its child namespaces, you can look at the MSDN Library 2002 years later, where in the "Namespace hierarchy" section, we can clearly see the hierarchy of each System.Xml namespace.
The above is a very simple example to show you how to access an XML document directly using C # and the System.Xml namespace. Of course, the code in this example is only an implementation method, the code has not been collated and optimized, here just want to be able to show you through this routine Visual C # A knowledge point, I hope to have more friends to provide better advice and suggestions.

Reading XML documents in C #

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.