C# XML XmlReader
To Read XML in C# or VB.net we need to use System.XML namespace. Here we will see how to read XML stored at C:\ drive using C#.net and VB.net. Every developer has come across the situation to read XML file programmatically. Let’s see basic example to read XML.
XMLReader has Static Create method which opens XML file to read. You can also use XML stream received by HttpWebResponse. You can also XMLReader to read RSS or ATOM feeds.
System.XML has very rich library to deal with XML. We will see XMLReader here.
C# XmlReader Example.
using System;
using System.Xml;
namespace Csharp.XMLReader.Example
{
class Program
{
static void Main(string[] args)
{
using (XmlReader reader = XmlReader.Create(@"C:\revenDemo.xml"))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "tutorials":
if(reader.Read())
Console.WriteLine("Value of tutorials element is: {0}", reader.Value.Trim());
break;
case "examples":
if (reader.Read())
Console.WriteLine("Value of examples element is: {0}", reader.Value.Trim());
break;
}
}
}
}
Console.ReadLine();
}
}
}
As you can see, we have stored XML file at C:\ HDD drive as Revendemo.xml. It contains tutorials and examples node. Below is the xml used in this example.
<?xml version="1.0" encoding="utf-8" ?>
<reven>
<tutorials>Asp.net XML Reader</tutorials>
<tutorials name="xxx">Element of XML example.</tutorials>
<tutorials>XMLNode list example.</tutorials>
<tutorials>Example and tutorials.</tutorials>
<tutorials>XML c# example.</tutorials>
<tutorials>C# tutorial</tutorials>
<examples>c# dateTime</examples>
<examples>C# reade file</examples>
<examples>C# write file</examples>
<examples>C# string</examples>
</reven>
VB.net XmlReader Example.
Imports System
Imports System.Xml
Namespace Csharp.XMLReader.Example
Class Program
Private Shared Sub Main(args As String())
Using reader As XmlReader = XmlReader.Create("C:\revenDemo.xml")
While reader.Read()
If reader.IsStartElement() Then
Select Case reader.Name
Case "tutorials"
If reader.Read() Then
Console.WriteLine("Value of tutorials element is: {0}", reader.Value.Trim())
End If
Exit Select
Case "examples"
If reader.Read() Then
Console.WriteLine("Value of examples element is: {0}", reader.Value.Trim())
End If
Exit Select
End Select
End If
End While
End Using
Console.ReadLine()
End Sub
End Class
End Namespace
Summery Here we saw how to read XML using XMLReader in C# and VB.net language.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5