Reading XML Files

 

The XmlReader and XmlTextReader classes are defined in the System.XML namespace.

The XmlTextReader class is derived from XmlReader class. The XmlTextReader class can be used to read the XML documents. The read function of this document reads the document until end of its nodes.

In this article, I will show you how to use XmlTextReader class to read an XML document and write data to the console.

Adding namspace Reference

Since Xml classes are defined in the System.XML namespace, so first thing you need to do is to Add the System.XML reference to the project.

using System.Xml;

Open an XML Document

The constructor of the XmlTextReader class opens an XML file. In this sample, I used an XML file called xmltest.xml in C/temp directory. You can download the attached file.

// Open an XML file
XmlTextReader reader = new XmlTextReader("C://temp//xmltest.xml");

Reading  Data

The Read method of the XmlTextReader class reads the data.

while ( reader.Read() )
{
Console.WriteLine(reader.Name);
}

Souce Code:   Attachment readxml1.cs 1 KB,  xmltest.xml 1 KB

namespace ReadXML
{
using System;
using System.Xml;
/// <summary>

///
Summary description for Class1.
/// </summary>

public class Class1
{
public Class1()
{
}
public static int Main(string[] args)
{
try
{
// Open an XML file
XmlTextReader reader = new XmlTextReader("C://temp//xmltest.xml");
while ( reader.Read() )
{
Console.WriteLine(reader.Name);
}
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}
return 0;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值