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

Definição

Lê o conteúdo do texto de um elemento num buffer de caracteres. Este método foi concebido para ler grandes fluxos de texto incorporado, chamando-os 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[]

O conjunto de caracteres que serve de buffer para onde o conteúdo do texto é escrito.

index
Int32

A posição buffer onde o método pode começar a escrever conteúdos de texto.

count
Int32

O número de caracteres a escrever em buffer.

Devoluções

O número de caracteres lidos. Isto pode acontecer 0 se o leitor não estiver posicionado num elemento ou se não houver mais conteúdo textual para devolver no contexto atual.

Exceções

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

O buffer valor é null.

index < 0 ou count< 0.

Exemplos

O exemplo seguinte lê-se 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 ficheiro 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>

Observações

Note

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

Esta é a forma mais eficiente de processar fluxos muito grandes de texto embutidos num documento XML. Em vez de alocar grandes objetos string, ReadChars devolve o conteúdo do texto um buffer de cada vez. Este método foi concebido para funcionar apenas em nós de elemento. Outros tipos de nós causam ReadChars o retorno 0de .

No XML seguinte, se o leitor estiver posicionado na etiqueta inicial, ReadChars volta test e posiciona o leitor após a etiqueta final.

<Item>test</Item>

ReadChars tem a seguinte funcionalidade:

  • Este método foi concebido para funcionar apenas com nós elemento. Outros tipos de nós causam ReadChars o retorno de 0.

  • Este método devolve o conteúdo real da personagem. Não há qualquer tentativa de resolver entidades, CDATA ou qualquer outra marcação encontrada. ReadChars devolve tudo entre a etiqueta inicial e a etiqueta final, incluindo a marcação.

  • ReadChars ignora a marcação XML que não está bem estruturada. Por exemplo, ao ler a seguinte cadeia <A>1<A>2</A>XML , ReadChars devolve 1<A>2</A>. (Devolve a marcação do par de elementos correspondente e ignora os outros.)

  • Este método não faz qualquer normalização.

  • Quando ReadChars chega ao fim do fluxo de caracteres, devolve o valor 0 e o leitor é posicionado após a tag final.

  • Os métodos de leitura de atributos não estão disponíveis enquanto se usa ReadChars.

Por exemplo, usando o seguinte XML:

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

O leitor é posicionado sobre o <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

Ver também