XmlTextReader.ReadString Método

Definição

Lê o conteúdo de um elemento ou de 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

Devoluções

O conteúdo do elemento ou do nó de texto. Esta pode ser uma cadeia vazia se o leitor estiver posicionado em algo que não seja um elemento ou nó de texto, ou se não houver mais conteúdo de texto para devolver no contexto atual.

Note: O nó de texto pode ser tanto um elemento como um nó de texto de atributo.

Exceções

Ocorreu um erro durante a análise do XML.

Foi tentada uma operação inválida.

Exemplos

O exemplo seguinte mostra o conteúdo textual de cada elemento.

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 ficheiro , elems.xmlcomo entrada.


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

Observações

Note

Recomendamos que crie instâncias XmlReader usando o método XmlReader.Create para aproveitar a nova funcionalidade.

Se posicionado num elemento, ReadString concatena todo o texto, espaços em branco significativos, espaços em branco e CData tipos de nós de secção e devolve os dados concatenados como conteúdo do elemento. Para quando é encontrada qualquer marcação, incluindo comentários e instruções de processamento. Isto pode ocorrer num modelo de conteúdo misto, ou quando uma etiqueta final de elemento é lida.

Se posicionado num nó de texto, ReadString realiza a mesma concatenação do nó de texto para a etiqueta final do elemento. Se o leitor estiver posicionado num nó de texto de atribuido, ReadString tem a mesma funcionalidade que se o leitor estivesse posicionado na etiqueta de início do elemento. Devolve todos os nós de texto dos elementos concatenados.

Aplica-se a

Ver também