XmlTextReader. With XmlTextReader we parse XML data. This type acts upon a string containing XML markup. A while-loop is needed to keep reading from the object.
using System;
using System.IO;
using System.Xml;
class Program
{
static void Main()
{
string input = @"<?xml version=""1.0"" encoding=""utf-16""?><List>
<Employee><ID>1</ID><First>David</First>
<Last>Smith</Last><Salary>10000</Salary></Employee>
<Employee><ID>3</ID><First>Mark</First>
<Last>Drinkwater</Last><Salary>30000</Salary></Employee>
<Employee><ID>4</ID><First>Norah</First>
<Last>Miller</Last><Salary>20000</Salary></Employee>
<Employee><ID>12</ID><First>Cecil</First>
<Last>Walker</Last><Salary>120000</Salary></Employee>
</List>";
using (StringReader stringReader = new StringReader(input))
using (XmlTextReader reader = new XmlTextReader(stringReader))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Employee":
Console.WriteLine();
break;
case "ID":
Console.WriteLine("ID: " + reader.ReadString());
break;
case "First":
Console.WriteLine("First: " + reader.ReadString());
break;
case "Last":
Console.WriteLine("Last: " + reader.ReadString());
break;
case "Salary":
Console.WriteLine("Salary: " + reader.ReadString());
break;
}
}
}
}
}
}ID: 1
First: David
Last: Smith
Salary: 10000
ID: 3
First: Mark
Last: Drinkwater
Salary: 30000
ID: 4
First: Norah
Last: Miller
Salary: 20000
ID: 12
First: Cecil
Last: Walker
Salary: 120000
XmlReader note. XmlReader and XmlTextReader are basically the same. When you call XmlTextReader.Create, an XmlReader is returned. The XmlTextReader type provides more constructors.
Summary. We looked at the XmlTextReader type. With XmlTextReader, we gain more constructors for using an XmlReader. These types can be used to develop fast parsers for XML files.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 28, 2022 (edit).