XmlTextReader.ReadString Método

Definição

Lê o conteúdo de um elemento ou um nó de texto como uma cadeia de caracteres.

public:
 override System::String ^ ReadString();
public override string ReadString ();
override this.ReadString : unit -> string
Public Overrides Function ReadString () As String

Retornos

String

O conteúdo do nó de elemento ou de texto. Essa poderá ser uma cadeia de caracteres vazia se o leitor estiver posicionado em algo diferente de um elemento ou nó de texto ou, se não houver nenhum outro conteúdo de texto para retornar no contexto atual.

Note: O nó de texto pode ser um elemento ou um nó de texto do atributo.

Exceções

Erro ao analisar o XML.

Ocorreu uma tentativa de uma operação inválida.

Exemplos

O exemplo a seguir exibe o conteúdo de texto de cada elemento.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlTextReader^ reader = nullptr;
   try
   {
      
      //Load the reader with the XML file.
      reader = gcnew XmlTextReader( "elems.xml" );
      
      //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 );
            else
            {
               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.
            }
         }
      }
   }
   finally
   {
      if ( reader != nullptr )
            reader->Close();
   }

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

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

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("elems.xml");

       //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);
                    }
                    else
                    {
               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.
           }
         }
       }
     }

     finally
     {
        if (reader != null)
          reader.Close();
      }
  }
} // End class
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        Dim reader As XmlTextReader = Nothing
        
        Try
            'Load the reader with the XML file.
            reader = New XmlTextReader("elems.xml")
            
            'Parse the XML and display the text content of each of the elements.
            While reader.Read()
                If reader.IsStartElement() Then
                    If reader.IsEmptyElement Then
                        Console.WriteLine("<{0}/>", reader.Name)
                    Else
                        Console.Write("<{0}>" + " ", reader.Name)
                        reader.Read() 'Read the start tag.
                        If (reader.IsStartElement())  'Handle nested elements.
                          Console.WriteLine()
                          Console.Write("<{0}>", reader.Name)
                        End If
                        Console.WriteLine(reader.ReadString()) 'Read the text content of the element.
                    End If
                End If
            End While
        
        
        Finally
            If Not (reader Is Nothing) Then
                reader.Close()
            End If
        End Try
    End Sub
End Class

O exemplo usa o arquivo, elems.xmlcomo entrada.


<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
  <misc/>
</book>

Comentários

Observação

A partir do .NET Framework 2.0, recomendamos que você crie XmlReader instâncias usando o XmlReader.Create método para aproveitar a nova funcionalidade.

Se posicionado em um elemento, ReadString concatena todo o texto, espaço em branco significativo, espaço em branco e CData tipos de nó de seção juntos e retorna os dados concatenados como o conteúdo do elemento. Ela é interrompida quando qualquer marcação é encontrada, incluindo comentários e instruções de processamento. Isso pode ocorrer em um modelo de conteúdo misto ou quando uma marca de fim de elemento for lida.

Se posicionado em um nó de texto, ReadString executa a mesma concatenação do nó de texto para a marca de extremidade do elemento. Se o leitor for posicionado em um nó de texto de atributo, o ReadString terá a mesma funcionalidade de um leitor posicionado na marca de início de elemento. Ele retornará todos os nós de texto de elemento concatenados.

Aplica-se a

Confira também