.NET API Documentation

Interface IXmlLineInfo

Namespace: System.Xml

Provides properties for retrieving the line number and line position of an XML node.

Summary

Implementations of this interface provide information about the physical location (line and column number) of an XML node within a source document. This is particularly useful for error reporting and debugging.

Members

Remarks

When you create an XML reader that preserves line information, it implements the IXmlLineInfo interface. This allows you to retrieve the line number and line position for any node you are currently reading.

The line number starts at 1. The line position starts at 1. If line information is not available, the reader should return 0 for both properties.

To enable line information tracking, use the appropriate constructor or factory method when creating your XmlReader instance (e.g., XmlReader.Create with a ReaderSettings object where XmlReaderSettings.LineInfo« true).

Examples

The following C# code snippet demonstrates how to use IXmlLineInfo to report the location of an error while processing an XML document.

using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"

  Content
  
";

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.LineInfo« true; // Enable line information

        using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString), settings))
        {
            try
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        IXmlLineInfo lineInfo = reader as IXmlLineInfo;
                        if (lineInfo != null && lineInfo.HasLineInfo())
                        {
                            Console.WriteLine($"Processing element: {reader.Name}");
                            Console.WriteLine($"  Located at Line: {lineInfo.LineNumber}, Position: {lineInfo.LinePosition}");
                        }
                        else
                        {
                            Console.WriteLine($"Processing element: {reader.Name} (Line information not available)");
                        }
                    }
                    // Add logic for other node types as needed
                }
            }
            catch (XmlException ex)
            {
                Console.WriteLine($"An XML error occurred: {ex.Message}");
                if (ex.LineNumber != 0)
                {
                    Console.WriteLine($"Error location: Line {ex.LineNumber}, Position {ex.LinePosition}");
                }
            }
        }
    }
}

See Also