- Back to Home »
- Windows Applications »
- XMLReader
Posted by :
Sudhir Chekuri
Thursday, 10 March 2016
XMLReader class is used to read the xml data
Below example is used to read data
from xml file
ReadText.xml
<?xml version="1.0" encoding="utf-8" ?>
<Header>
<article
name="backgroundworker">
Example text.
</article>
<article
name="threadpool">
More text.
</article>
<article></article>
<article>Final
text.</article>
</Header>
Output
Start <Header> element.
Start <article> element.
Has
attribute name: backgroundworker
Text node: Example text.
Start <article> element.
Has
attribute name: threadpool
Text node: More text.
Start <article> element.
Text node:
Start <article> element.
Text node: Final text.
Code
using System;
using System.Xml;
class Program
{
static void Main()
{
// Create an XML reader for this
file.
using (XmlReader reader = XmlReader.Create("ReadText.xml"))
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element
name and switch on it.
switch (reader.Name)
{
case "Header":
// Detect this element.
Console.WriteLine("Start <Header>
element.");
break;
case "article":
// Detect this article element.
Console.WriteLine("Start <article>
element.");
// Search for the attribute name
on this current node.
string attribute = reader["name"];
if (attribute != null)
{
Console.WriteLine(" Has attribute name: " + attribute);
}
// Next read will contain text.
if (reader.Read())
{
Console.WriteLine(" Text node: " + reader.Value.Trim());
}
break;
}
}
}
}
Console.ReadKey();
}