.NET API Documentation

System.Xml Namespace

XmlReader.ReadContentAsDecimal Method

public decimal ReadContentAsDecimal ();

Summary

Reads the current node’s content as a decimal.

This method reads the content of the current node as a decimal. When it is positioned on a text node, it attempts to parse the text node as a decimal number.

Returns

decimal: The content of the current node as a decimal.

Exceptions

  • InvalidOperationException: The current node is not an attribute or text node.
  • XmlException: Unable to convert the string to a decimal.

Remarks

This method reads content as a decimal.

If the current node is an attribute or a text node, it attempts to parse the content as a decimal. If the content cannot be parsed as a decimal, an XmlException is thrown.

The XmlReader advances to the next node after calling this method.

Example

The following example shows how to read decimal content from an XML document using ReadContentAsDecimal.


using System;
using System.Xml;

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

        using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString)))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "value")
                    {
                        if (reader.Read()) // Move to the text node
                        {
                            try
                            {
                                decimal decimalValue = reader.ReadContentAsDecimal();
                                Console.WriteLine($"Found decimal value: {decimalValue}");
                            }
                            catch (XmlException ex)
                            {
                                Console.WriteLine($"Error reading decimal: {ex.Message}");
                            }
                        }
                    }
                }
            }
        }
    }
}