XmlTextReader.ReadChars(Char[], Int32, Int32) Metodo

Definizione

Legge il contenuto di testo di un elemento in un buffer di caratteri. Il metodo consente di leggere flussi di notevoli dimensioni di testo incorporato chiamandolo in successione.

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

Parametri

buffer
Char[]

Matrice di caratteri che funge da buffer in cui viene scritto il contenuto di testo.

index
Int32

Posizione all'interno di buffer in cui il metodo può iniziare a scrivere contenuti di testo.

count
Int32

Numero di caratteri da scrivere in buffer.

Restituisce

Numero di caratteri letti. Può essere 0 se il lettore non è posizionato su un elemento o se non ci sono più contenuto da restituire nel contesto corrente.

Eccezioni

count è maggiore dello spazio specificato nel buffer (dimensione buffer - index).

Il valore buffer è null.

index< 0 o count< 0.

Esempio

Nell'esempio seguente viene letto in XML usando 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

Nell'esempio viene utilizzato il file items.xml come input.


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

Commenti

Nota

A partire da .NET Framework 2.0, è consigliabile creare XmlReader istanze usando il XmlReader.Create metodo per sfruttare nuove funzionalità.

Questo è il modo più efficiente per elaborare flussi di testo molto grandi incorporati in un documento XML. Anziché allocare oggetti stringa di grandi dimensioni, ReadChars restituisce un contenuto di testo alla volta. Questo metodo è progettato per funzionare solo sui nodi dell'elemento. Altri tipi di nodo causano ReadChars la restituzione 0di .

Nel codice XML seguente, se il lettore è posizionato sul tag iniziale, ReadChars restituisce test e posiziona il lettore dopo il tag finale.

<Item>test</Item>

ReadChars ha le funzionalità seguenti:

  • Questo metodo è progettato per funzionare solo sui nodi dell'elemento. Altri tipi di nodo causano ReadChars la restituzione di 0.

  • Questo metodo restituisce il contenuto effettivo del carattere. Non esiste alcun tentativo di risolvere entità, CDATA o altri markup rilevati. ReadChars restituisce tutti gli elementi tra il tag iniziale e il tag finale, incluso il markup.

  • ReadChars ignora il markup XML che non è ben formato. Ad esempio, quando si legge la stringa <A>1<A>2</A>XML seguente, ReadChars restituisce 1<A>2</A>. Restituisce il markup dalla coppia di elementi corrispondente e ignora altri elementi.

  • Questo metodo non esegue alcuna normalizzazione.

  • Quando ReadChars ha raggiunto la fine del flusso di caratteri, restituisce il valore 0 e il lettore viene posizionato dopo il tag finale.

  • I metodi di lettura degli attributi non sono disponibili durante l'uso di ReadChars.

Ad esempio, usando il codice XML seguente:

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

Il lettore viene posizionato sull'elemento <item> alla fine del ciclo 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.
 }
}

Si applica a

Vedi anche