XmlValidatingReader.ReadString Método

Definição

Lê o conteúdo de um elemento ou nó de texto como uma cadeia de caracteres.Reads the contents of an element or text node as a string.

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.The contents of the element or text node. 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.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.


O nó de texto pode ser um elemento ou um nó de texto do atributo.The text node can be either an element or an attribute text node.

Exemplos

O exemplo a seguir exibe o conteúdo de texto de cada um dos elementos.The following example displays the text content of each of the elements.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlTextReader^ txtreader = nullptr;
   XmlValidatingReader^ reader = nullptr;
   try
   {
      
      //Implement the readers.
      txtreader = gcnew XmlTextReader( "elems.xml" );
      reader = gcnew 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 );
            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 txtreader = null;
    XmlValidatingReader reader = null;

    try
    {
       //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);
                    }
                    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
Imports System.IO
Imports System.Xml

Public Class Sample
   
   Public Shared Sub Main()
      Dim txtreader As XmlTextReader = Nothing
      Dim reader As XmlValidatingReader = Nothing
      
      Try
         '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() 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.xml , como entrada.The example uses the file, elems.xml, as input.

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

Comentários

Observação

A XmlValidatingReader classe está obsoleta no .NET Framework 2,0.The XmlValidatingReader class is obsolete in .NET Framework 2.0. Você pode criar uma instância de validação XmlReader usando a XmlReaderSettings classe e o Create método.You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. Para obter mais informações, consulte a seção de Comentários da página de referência XmlReader.For more information, see the Remarks section of the XmlReader reference page.

Se estiver posicionado em um elemento, ReadString concatena todos os tipos de nó de texto, espaço em branco significativos, espaço em branco e CDATA e retorna os dados concatenados como o conteúdo do elemento.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. O leitor para quando qualquer marcação é encontrada, incluindo comentários e instruções de processamento.The reader stops when any markup is encountered, including comments and processing instructions. Isso pode ocorrer em um modelo de conteúdo misto ou quando uma marca de fim de elemento for lida.This could occur in a mixed content model, or when an element end tag is read.

Se posicionado em um nó de texto, ReadString o executará a mesma concatenação do nó de texto para a marca de fim do elemento.If positioned on a text node, ReadString performs the same concatenation from the text node to the element end tag. 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.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. Ele retornará todos os nós de texto de elemento concatenados.It returns all the concatenated element text nodes.

A EntityHandling propriedade determina como o ReadString funciona da seguinte maneira:The EntityHandling property determines how ReadString works as follows:

ValorValue DescriçãoDescription
ExpandEntitiesExpandEntities Retorna as entidades de caractere expandido e geral.Returns expanded character and general entities. Esse é o padrão.This is the default.
ExpandCharEntitiesExpandCharEntities Retorna o conteúdo do texto até, mas não incluindo, uma referência de entidade geral.Returns the text content up to but not including a general entity reference. Isso significa que uma entidade geral faz com que ReadString pare.This means a general entity causes ReadString to stop. Você deve chamar Read para Step sobre a referência de entidade.You must call Read to step over the entity reference.

Aplica-se a

Confira também