System.Xml.XmlNodeReader.ReadDateTime()

.NET API Documentation

Description

Reads the current node's value as a DateTime. This method supports a wide range of XML date and time formats.

public override DateTime ReadDateTime( );

Parameters

This method does not take any parameters.

Return Value

The value of the current node as a DateTime. If the node does not contain a valid DateTime, an exception is thrown.

Exceptions

  • XmlException: Thrown if the current node's value cannot be parsed as a DateTime.
  • InvalidOperationException: Thrown if the current node is not an attribute node or an element node with a value.

Remarks

The XmlNodeReader class provides a forward-only, read-only view of an XML document as a sequence of XmlReader nodes. The ReadDateTime method is useful for extracting date and time information from specific XML elements or attributes.

The method attempts to parse the node's value using standard date and time formatting rules. It can handle formats such as:

  • yyyy-MM-ddTHH:mm:ss.fffffffK (ISO 8601)
  • MM/dd/yyyy HH:mm:ss
  • dd-MMM-yyyy
  • And other common representations.

Ensure that the XML node you are attempting to read contains a value that can be unambiguously interpreted as a date and time before calling this method.

Example

The following example demonstrates how to use the ReadDateTime method to read a date and time value from an XML element.

XML:

<event>
    <name>Conference</name>
    <startTime>2023-10-27T09:00:00Z</startTime>
</event>

C#:

using System;
using System.Xml;

public class XmlNodeReaderExample
{
    public static void Main(string[] args)
    {
        string xmlString = @"
        <event>
            <name>Conference</name>
            <startTime>2023-10-27T09:00:00Z</startTime>
        </event>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);

        // Use XmlNodeReader to read the document
        using (XmlReader reader = new XmlNodeReader(doc))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "startTime")
                {
                    // Move to the element's value
                    if (reader.Read())
                    {
                        try
                        {
                            DateTime eventTime = reader.ReadDateTime();
                            Console.WriteLine($"Event Start Time: {eventTime}");
                        }
                        catch (XmlException ex)
                        {
                            Console.WriteLine($"Error reading DateTime: {ex.Message}");
                        }
                    }
                }
            }
        }
    }
}

See Also