XmlNodeReader.ReadDecimal() Method

Summary

Reads the current node's value as a decimal. When you are in an element, this method positions the reader on the text node that contains the value. When you are in an attribute, this method positions the reader on the attribute value.

Syntax

            
public decimal ReadDecimal();
            
        

Parameters

This method takes no parameters.

Returns

decimal

The value of the current node as a decimal.

Exceptions

Remarks

This method attempts to convert the value of the current node to a decimal. If the value cannot be parsed as a decimal, a System.FormatException is thrown.

This method is useful for reading numeric values from XML documents, especially when dealing with financial data or precise measurements.

Note: Ensure that the current node's value is a valid representation of a decimal number before calling this method to avoid unexpected exceptions. Use the NodeType property to check the current node type and Value property to inspect the string representation of the value.

Example

The following example demonstrates how to use the ReadDecimal() method to read a decimal value from an XML element.

            
using System;
using System.Xml;

public class Example
{
    public static void Main()
    {
        string xmlString = @"<root><price>123.45</price></root>";

        using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "price")
                    {
                        reader.Read(); // Move to the text node containing the value
                        decimal price = reader.ReadDecimal();
                        Console.WriteLine("Price: {0}", price);
                    }
                }
            }
        }
    }
}