.NET Documentation

XmlReader.ReadValueAsString Method

Reads the value of the current node as a string.

Syntax

public string ReadValueAsString();

Parameters

This method has no parameters.

Return Value

The value of the current node as a string.

Remarks

This method can be called on any node type. It returns an empty string for attributes that have no value.

If the current node is an attribute, it returns the attribute value. If the current node is an element, it returns the concatenated text content of all child text nodes. If the current node is a processing instruction or comment, it returns the text content of the instruction or comment.

If the current node is of a type that does not have a value (e.g., an XML declaration or document type), it returns an empty string.

Exceptions

InvalidOperationException
Thrown if the XmlReader is not positioned on a node that has a value.

Example

The following example demonstrates how to use the ReadValueAsString method to retrieve the value of an element.

using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"<root><element attribute=""someValue"">Node text</element></root>";

        using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString)))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "element")
                    {
                        Console.WriteLine($"Element Name: {reader.Name}");
                        Console.WriteLine($"Attribute Value: {reader.GetAttribute("attribute")}");

                        // Read the value of the element
                        if (reader.Read()) // Move to the text node
                        {
                            Console.WriteLine($"Element Value: {reader.Value}");
                            // Alternatively, using ReadValueAsString()
                            // Console.WriteLine($"Element Value (using ReadValueAsString): {reader.ReadValueAsString()}");
                        }
                    }
                }
            }
        }
    }
}

See Also

This method is a convenient way to get the string representation of a node's value. For more control over how values are read (e.g., into specific data types), consider using other methods like ReadElementContentAsString() or ReadContentAsInt().