ZetCode

C# XmlReader

last modified July 5, 2020

C# XmlReader tutorial shows how to use read XML data in C# with XmlReader.

XmlReader

XmlReader represents a reader that provides fast, noncached, forward-only access to XML data.

The XmlReader is available in the System.Xml namespace.

C# XmlReader example

The following example creates a simple C# XmlReader.

data.xml
<?xml version="1.0" encoding="utf-8"?>
<value>6</value>

We have a very simple XML file.

Program.cs
using System;
using System.Xml;

namespace Simple
{
    class Program
    {
        static void Main(string[] args)
        {
            using var reader = XmlReader.Create("data.xml");

            reader.MoveToContent();
            var data = reader.ReadElementContentAsString();

            Console.WriteLine(data);
        }
    }
}

In the example, we read the value from the simple XML document with XmlReader.

using var reader = XmlReader.Create("data.xml");

The XmlReader is created with the Create method.

reader.MoveToContent();

The MoveToContent method skips the non-content nodes and moves to the next content node or to the end of the file.

var data = reader.ReadElementContentAsString();

The ReadElementContentAsString reads the current element and returns the contents as a string.

$ dotnet run 
6

This is the output.

C# XmlReader ReadToFollowing

The ReadToFollowing method advances the reader to the next following element that matches the specified name and returns true if a matching element is found.

books.xml
<bookstore>
    <book genre='Science Fiction'>
        <title>Dune</title>
        <author>Frank Herbert</author>
        <price>8.99</price>
    </book>
    <book genre='Novel'>
        <title>Old Goriot</title>
        <author>Honoré de Balzac</author>
        <price>9.0</price>
    </book>
</bookstore>

This XML file contains books.

Program.cs
using System;
using System.Xml;

namespace Simple
{
    class Program
    {
        static void Main(string[] args)
        {
            using var reader = XmlReader.Create("books.xml");

            reader.ReadToFollowing("book");

            do
            {
                reader.MoveToFirstAttribute();
                Console.WriteLine($"genre: {reader.Value}");

                reader.ReadToFollowing("title");
                Console.WriteLine($"title: {reader.ReadElementContentAsString()}");

                reader.ReadToFollowing("author");
                Console.WriteLine($"author: {reader.ReadElementContentAsString()}");

                reader.ReadToFollowing("price");
                Console.WriteLine($"price: {reader.ReadElementContentAsString()}");

                Console.WriteLine("-------------------------");

            } while (reader.ReadToFollowing("book"));
        }
    }
}

The example reads two books from the books.xml file.

reader.ReadToFollowing("book");

We start by advancing to the first book element.

reader.MoveToFirstAttribute();
Console.WriteLine($"genre: {reader.Value}");

We read the genre attribute with MoveToFirstAttribute.

reader.ReadToFollowing("title");
Console.WriteLine($"title: {reader.ReadElementContentAsString()}");

We read the contents of the title element.

} while (reader.ReadToFollowing("book"));

With the while loop we go through all the book elements in the XML file.

$ dotnet run
genre: Science Fiction
title: Dune
author: Frank Herbert
price: 8.99
-------------------------
genre: Novel
title: Old Goriot
author: Honoré de Balzac
price: 9.0
-------------------------

This is the output.

C# XmlReader Read

The Read method reads the next node from the stream.

products.xml
<?xml version="1.0" encoding="utf-8"?>
<products>
    <product>
        <id>1</id>
        <name>Product A</name>
        <price>1200</price>
    </product>

    <product>
        <id>2</id>
        <name>Product B</name>
        <price>1100</price>
    </product>
</products>

In this XML file, we have products.

Program.cs
using System;
using System.Xml;

namespace XmlRead
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Products");
            Console.WriteLine("----------------------");

            using var reader = XmlReader.Create("products.xml");

            reader.MoveToContent();

            while (reader.Read())
            {
                string result = reader.NodeType switch
                {
                    XmlNodeType.Element when reader.Name == "product" => $"{reader.Name}\n",
                    XmlNodeType.Element => $"{reader.Name}: ",
                    XmlNodeType.Text => $"{reader.Value}\n",
                    XmlNodeType.EndElement when reader.Name == "product" =>  "----------------------\n",
                    _ => ""
                };

                Console.Write(result);
                
            }
        }
    }
}

The example presents the classic approach to reading XML files. We read the document node by node and in the switch statement or expression deal with the particular element, text, attribute or other type of node.

reader.MoveToContent();

We skip the root element and go right to the content of the document.

while (reader.Read())
{

The Read method reads the next node until the end of the document.

string result = reader.NodeType switch
{
    XmlNodeType.Element when reader.Name == "product" => $"{reader.Name}\n",
    XmlNodeType.Element => $"{reader.Name}: ",
    XmlNodeType.Text => $"{reader.Value}\n",
    XmlNodeType.EndElement when reader.Name == "product" =>  "----------------------\n",
    _ => ""
};

We use the switch expression to process the different node types. The Name property gives name of the current node. The Value property gets the text value of the current node.

$ dotnet run
Products
----------------------
product
id: 1
name: Product A
price: 1200
----------------------
product
id: 2
name: Product B
price: 1100
----------------------

This is the output.

Visit C# tutorial or list all C# tutorials.