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

Definición

Lee el contenido de texto de un elemento en un búfer de caracteres. Este método se ha diseñado para leer grandes flujos de texto incrustado llamando sucesivamente al método.

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[]

Matriz de caracteres que sirve como búfer en el que se escribe el contenido de texto.

index
Int32

Posición dentro de buffer donde el método puede comenzar a escribir contenido de texto.

count
Int32

Número de caracteres que se van a escribir en el buffer.

Devoluciones

Número de caracteres que se han leído. Puede ser 0 si el lector no está situado en un elemento o si no hay más contenido de texto para devolver en el contexto actual.

Excepciones

count es mayor que el espacio especificado en buffer (tamaño de búfer - index).

El valor buffer es null.

index< 0 o count< 0.

Ejemplos

En el ejemplo siguiente se lee en XML mediante ReadChars.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;

// Reads an XML document using ReadChars
int main()
{
   XmlTextReader^ reader = nullptr;
   String^ filename = "items.xml";
   try
   {
      
      // Declare variables used by ReadChars
      array<Char>^buffer;
      int iCnt = 0;
      int charbuffersize;
      
      // Load the reader with the data file.  Ignore white space.
      reader = gcnew XmlTextReader( filename );
      reader->WhitespaceHandling = WhitespaceHandling::None;
      
      // Set variables used by ReadChars.
      charbuffersize = 10;
      buffer = gcnew array<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:{0}", iCnt );
         Console::WriteLine( "  Buffer: [{0}]", gcnew String( buffer,0,iCnt ) );
         
         // Clear the buffer.
         Array::Clear( buffer, 0, charbuffersize );
      }
   }
   finally
   {
      if ( reader != nullptr )
            reader->Close();
   }

}
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

En el ejemplo se utiliza como entrada el archivo items.xml.


<?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>

Comentarios

Nota

A partir de .NET Framework 2.0, se recomienda crear XmlReader instancias mediante el XmlReader.Create método para aprovechar las nuevas funcionalidades.

Esta es la manera más eficaz de procesar secuencias de texto muy grandes incrustadas en un documento XML. En lugar de asignar objetos de cadena grandes, ReadChars devuelve un búfer de contenido de texto a la vez. Este método está diseñado para funcionar solo en nodos de elemento. Otros tipos de nodo hacen que ReadChars devuelva 0.

En el siguiente XML, si el lector se coloca en la etiqueta de inicio, ReadChars devuelve test y coloca el lector después de la etiqueta final.

<Item>test</Item>

ReadChars tiene la siguiente funcionalidad:

  • Este método está diseñado para funcionar solo en nodos de elemento. Otros tipos de nodo hacen que ReadChars devuelva 0.

  • Este método devuelve el contenido de caracteres real. No hay ningún intento de resolver entidades, CDATA ni ningún otro marcado encontrado. ReadChars devuelve todo entre la etiqueta de inicio y la etiqueta final, incluido el marcado.

  • ReadChars omite el marcado XML que no tiene el formato correcto. Por ejemplo, al leer la siguiente cadena <A>1<A>2</A>XML , ReadChars devuelve 1<A>2</A>. (Devuelve el marcado del par de elementos coincidente y omite otros).

  • Este método no realiza ninguna normalización.

  • Cuando ReadChars ha llegado al final de la secuencia de caracteres, devuelve el valor 0 y el lector se coloca después de la etiqueta final.

  • Los métodos de lectura de atributos no están disponibles al usar ReadChars.

Por ejemplo, con el siguiente CÓDIGO XML:

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

El lector se coloca en el <item> elemento al final del bucle 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.
 }
}

Se aplica a

Consulte también