Use c # to read xml files

Source: Internet
Author: User
The XmlReader and XmlTextReader classes are defined in the System. XML namespace.
The XmlTextReader class is derived from the XmlReader class. The XmlTextReader class can be used to read XML documents. This type of Read method reads this document until its node ends.
In this article, we will demonstrate how to use the XmlTextReader class to read an XML document and output data to the console.
Add namespace reference
Because Xml classes are defined in the System. Xml namespace, the first thing to do is to add a reference to System. Xml in the project.
Using System. Xml;
Open an XML document
The XmlTextReader class constructor opens an XML file. In this example, a file named xmltest. xml is used and stored in the C: emp directory. You can download this attachment.
// Open an XML file
XmlTextReader reader = new XmlTextReader ("C: tempxmltest. xml ");
Read Data
The Read method of the XmlTextReader class reads data.
While (reader. Read ())
{
Console. WriteLine (reader. Name );
}
Source code:
Attachment
CS Code
XML file
Namespace ReadXML
{
Using System;
Using System. Xml;
Public static int Main (string [] args)
{
Try
{
// Open an XML file
XmlTextReader reader = new XmlTextReader ("C: tempxmltest. xml ");
While (reader. Read ())
{
Console. WriteLine (reader. Name );
}
    
}
Catch (Exception e)
{
Console. WriteLine ("Exception: {0}", e. ToString ());
}
Return 0;
}
}
}
 

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.