XmlTextReader.ReadChars(Char[], Int32, Int32) Método

Definição

Lê o conteúdo de texto de um elemento em um buffer de caracteres. Esse método foi projetado para ler grandes fluxos de texto inserido chamando-o sucessivamente.

public:
 int ReadChars(cli::array <char> ^ buffer, int index, int count);
public int ReadChars(char[] buffer, int index, int count);
member this.ReadChars : char[] * int * int -> int
Public Function ReadChars (buffer As Char(), index As Integer, count As Integer) As Integer

Parâmetros

buffer
Char[]

A matriz de caracteres que serve como o buffer no qual o conteúdo do texto é gravado.

index
Int32

A posição na buffer qual o método pode começar a escrever conteúdo de texto.

count
Int32

O número de caracteres a serem gravados buffer.

Retornos

O número de caracteres lidos. Isso pode ser 0 se o leitor não estiver posicionado em um elemento ou se não houver mais conteúdo de texto a ser retornado no contexto atual.

Exceções

count é maior que o espaço especificado no (tamanho do buffer buffer – index).

O buffer valor é null.

index < 0 ou count< 0.

Exemplos

O exemplo a seguir lê em XML usando ReadChars.

using System;
using System.Xml;

// Reads an XML document using ReadChars

public class Sample {

  private const String filename = "items.xml";

  public static void Main() {

    XmlTextReader reader = null;

    try {

      // Declare variables used by ReadChars
      Char []buffer;
      int iCnt = 0;
      int charbuffersize;

      // Load the reader with the data file.  Ignore white space.
      reader = new XmlTextReader(filename);
      reader.WhitespaceHandling = WhitespaceHandling.None;

      // Set variables used by ReadChars.
      charbuffersize = 10;
      buffer = new Char[charbuffersize];

      // Parse the file.  Read the element content
      // using the ReadChars method.
      reader.MoveToContent();
      while ( (iCnt = reader.ReadChars(buffer,0,charbuffersize)) > 0 ) {
        // Print out chars read and the buffer contents.
        Console.WriteLine ("  Chars read to buffer:" + iCnt);
        Console.WriteLine ("  Buffer: [{0}]", new String(buffer,0,iCnt));
        // Clear the buffer.
        Array.Clear(buffer,0,charbuffersize);
      }
    }
    finally {
      if (reader!=null)
        reader.Close();
    }
  }
} // End class
Imports System.Xml

' Reads an XML document using ReadChars
Public Class Sample
    Private Const filename As String = "items.xml"
    
    Public Shared Sub Main()
        Dim reader As XmlTextReader = Nothing
        
        Try
            ' Declare variables used by ReadChars
            Dim buffer() As Char
            Dim iCnt As Integer = 0
            Dim charbuffersize As Integer
            
            ' Load the reader with the data file.  Ignore white space.
            reader = New XmlTextReader(filename)
            reader.WhitespaceHandling = WhitespaceHandling.None
            
            ' Set variables used by ReadChars.
            charbuffersize = 10
            buffer = New Char(charbuffersize) {}
            
            ' Parse the file.  Read the element content  
            ' using the ReadChars method.
            reader.MoveToContent()
            iCnt = reader.ReadChars(buffer,0,charbuffersize)
            while (iCnt > 0)
              ' Print out chars read and the buffer contents.
              Console.WriteLine("  Chars read to buffer:" & iCnt)
              Console.WriteLine("  Buffer: [{0}]", New String(buffer, 0, iCnt))
              ' Clear the buffer.
              Array.Clear(buffer, 0, charbuffersize)
              iCnt = reader.ReadChars(buffer,0,charbuffersize)
           end while

        Finally
            If Not (reader Is Nothing) Then
                reader.Close()
            End If
        End Try
    End Sub 
End Class

O exemplo usa o items.xml arquivo como entrada.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: A</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

Comentários

Note

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

Essa é a maneira mais eficiente de processar fluxos muito grandes de texto inseridos em um documento XML. Em vez de alocar objetos de cadeia de caracteres grandes, ReadChars retorna um buffer de conteúdo de texto por vez. Esse método foi projetado para funcionar somente em nós de elemento. Outros tipos de nó causam ReadChars o retorno 0.

No XML a seguir, se o leitor estiver posicionado na marca inicial, ReadChars retornará test e posicionará o leitor após a marca final.

<Item>test</Item>

ReadChars tem a seguinte funcionalidade:

  • Esse método foi projetado apenas para funcionar em nós de elemento. Outros tipos de nó causam ReadChars o retorno 0.

  • Esse método retorna o conteúdo real do caractere. Não há nenhuma tentativa de resolver entidades, CDATA ou qualquer outra marcação encontrada. ReadChars retorna tudo entre a marca inicial e a marca de término, incluindo marcação.

  • ReadChars ignora a marcação XML que não está bem formada. Por exemplo, ao ler a seguinte cadeia de <A>1<A>2</A>caracteres XML, ReadChars retorna 1<A>2</A>. (Ele retorna marcação do par de elementos correspondentes e ignora outros.)

  • Esse método não faz nenhuma normalização.

  • Quando ReadChars chegar ao final do fluxo de caracteres, ele retornará o valor 0 e o leitor será posicionado após a marca final.

  • Os métodos de leitura de atributo não estão disponíveis durante o uso ReadChars.

Por exemplo, usando o seguinte XML:

<thing>
 some text
</thing>
<item>
</item>

O leitor é posicionado no <item> elemento no final do loop while.

if (XmlNodeType.Element == reader.NodeType && "thing" == reader.Name)
{
 while(0 != reader.ReadChars(buffer, 0, 1)
 {
 // Do something.
 // Attribute values are not available at this point.
 }
}

Aplica-se a

Confira também