XmlDictionaryReader

.NET API Documentation

Namespace System.Xml
Assembly System.Xml.dll
Language C#

Class XmlDictionaryReader

Represents a reader that provides fast, XML dictionary-based, forward-only access to a stream of XML data. This class is optimized for scenarios where many XML documents share a common set of element and attribute names.

Inheritance

Object
    XmlReader
        XmlDictionaryReader

Remarks

The XmlDictionaryReader class is particularly useful in scenarios involving the Simple Object Access Protocol (SOAP) or other web services where messages often contain repetitive element and attribute names. By using a dictionary to represent these names, the reader can achieve significant performance improvements by avoiding repeated string parsing and comparisons. You can create an instance of XmlDictionaryReader using the static factory methods provided by the XmlDictionaryReader class, such as Create.

Methods

The XmlDictionaryReader class inherits methods from XmlReader and provides its own set of specialized methods. Some key methods include:

Syntax

public abstract class XmlDictionaryReader : XmlReader

Examples

Reading XML with XmlDictionaryReader

The following example demonstrates how to create and use an XmlDictionaryReader to read an XML string.

using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"<root><item id='1'>Example Item</item></root>";

        using (XmlDictionaryReader reader = XmlDictionaryReader.Create(
            new System.IO.StringReader(xmlString)))
        {
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.WriteLine("Element: {0}", reader.Name);
                        if (reader.HasAttributes)
                        {
                            while (reader.MoveToNextAttribute())
                            {
                                Console.WriteLine("  Attribute: {0} = {1}", reader.Name, reader.Value);
                            }
                            reader.MoveToElement(); // Move back to the element node
                        }
                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine("Text: {0}", reader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        Console.WriteLine("End Element: {0}", reader.Name);
                        break;
                }
            }
        }
    }
}

Related Topics