XmlValidatingReader.ReadString Method ()


Reads the contents of an element or text node as a string.

Namespace:   System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public override string ReadString()

Return Value

Type: System.String

The contents of the element or text node. This can be an empty string if the reader is positioned on something other than an element or text node, or if there is no more text content to return in the current context.


The text node can be either an element or an attribute text node.


The XmlValidatingReader class is obsolete in .NET Framework 2.0. You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. For more information, see the Remarks section of the XmlReader reference page.

If positioned on an element, ReadString concatenates all text, significant white space, white space, and CDATA section node types together and returns the concatenated data as the element content. The reader stops when any markup is encountered, including comments and processing instructions. This could occur in a mixed content model, or when an element end tag is read.

If positioned on a text node, ReadString performs the same concatenation from the text node to the element end tag. If the reader is positioned on an attribute text node, ReadString has the same functionality as if the reader were position on the element start tag. It returns all the concatenated element text nodes.

The EntityHandling property determines how ReadString works as follows:




Returns expanded character and general entities. This is the default.


Returns the text content up to but not including a general entity reference. This means a general entity causes ReadString to stop. You must call Read to step over the entity reference.

The following example displays the text content of each of the elements.

using System;
using System.IO;
using System.Xml;

public class Sample 
  public static void Main()
    XmlTextReader txtreader = null;
    XmlValidatingReader reader = null;

       //Implement the readers.
       txtreader = new XmlTextReader("elems.xml");
       reader = new XmlValidatingReader(txtreader);

       //Parse the XML and display the text content of each of the elements.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.IsEmptyElement)
              Console.WriteLine("<{0}/>", reader.Name);
               Console.Write("<{0}> ", reader.Name);
               reader.Read(); //Read the start tag.
               if (reader.IsStartElement())  //Handle nested elements.
                   Console.Write("\r\n<{0}>", reader.Name);
               Console.WriteLine(reader.ReadString());  //Read the text content of the element.


        if (reader != null)

} // End class

The example uses the file, elems.xml, as input.

  <title>Pride And Prejudice</title>

.NET Framework
Available since 1.1
Return to top