XmlReader.Read Método

Definição

Quando substituído em uma classe derivada, lê o próximo nó do fluxo.When overridden in a derived class, reads the next node from the stream.

public:
 abstract bool Read();
public abstract bool Read ();
abstract member Read : unit -> bool
Public MustOverride Function Read () As Boolean

Retornos

Boolean

true se o próximo nó foi lido com êxito; caso contrário, false.true if the next node was read successfully; otherwise, false.

Exceções

Erro ao analisar o XML.An error occurred while parsing the XML.

Um método XmlReader foi chamado antes do término de uma operação assíncrona anterior.An XmlReader method was called before a previous asynchronous operation finished. Nesse caso, InvalidOperationException será gerado com a mensagem “Uma operação assíncrona já está em andamento”.In this case, InvalidOperationException is thrown with the message "An asynchronous operation is already in progress."

Exemplos

O exemplo a seguir lê um arquivo XML e exibe cada um dos nós:The following example reads an XML file and displays each of the nodes:

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create("items.xml", settings);

reader.MoveToContent();
  // Parse the file and display each of the nodes.
  while (reader.Read()) {
    switch (reader.NodeType) {
      case XmlNodeType.Element:
          Console.Write("<{0}>", reader.Name);
          break;
      case XmlNodeType.Text:
          Console.Write(reader.Value);
          break;
       case XmlNodeType.CDATA:
           Console.Write("<![CDATA[{0}]]>", reader.Value);
           break;
       case XmlNodeType.ProcessingInstruction:
           Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
           break;
       case XmlNodeType.Comment:
           Console.Write("<!--{0}-->", reader.Value);
           break;
       case XmlNodeType.XmlDeclaration:
           Console.Write("<?xml version='1.0'?>");
           break;
       case XmlNodeType.Document:
           break;
       case XmlNodeType.DocumentType:
           Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
           break;
       case XmlNodeType.EntityReference:
           Console.Write(reader.Name);
           break;
       case XmlNodeType.EndElement:
           Console.Write("</{0}>", reader.Name);
           break;
   }
}
Dim settings As New XmlReaderSettings()
settings.DtdProcessing = DtdProcessing.Parse
Dim reader As XmlReader = XmlReader.Create("items.xml", settings)
reader.MoveToContent()
' Parse the file and display each of the nodes.
While reader.Read()
  Select Case reader.NodeType
    Case XmlNodeType.Element
      Console.Write("<{0}>", reader.Name)
    Case XmlNodeType.Text
      Console.Write(reader.Value)
    Case XmlNodeType.CDATA
      Console.Write("<![CDATA[{0}]]>", reader.Value)
    Case XmlNodeType.ProcessingInstruction
      Console.Write("<?{0} {1}?>", reader.Name, reader.Value)
    Case XmlNodeType.Comment
      Console.Write("<!--{0}-->", reader.Value)
    Case XmlNodeType.XmlDeclaration
      Console.Write("<?xml version='1.0'?>")
    Case XmlNodeType.Document
    Case XmlNodeType.DocumentType
      Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value)
    Case XmlNodeType.EntityReference
      Console.Write(reader.Name)
    Case XmlNodeType.EndElement
      Console.Write("</{0}>", reader.Name)
  End Select
End While

O exemplo usa o items.xml arquivo.The sample uses the items.xml file.

<?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 a char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

Saída:Output:

<Item>Test with an entity: 123</Item><Item>Test with a child element <more> stuff</Item><Item>Test with a CDATA section <![CDATA[<456>]]> def</Item><Item>Test with a char entity: A</Item><!-- Fourteen chars in this element.--><Item>1234567890ABCD</Item></Items>

Comentários

Quando um XmlReader é criado e inicializado pela primeira vez, não há informações disponíveis.When an XmlReader is first created and initialized, there is no information available. Você deve chamar Read para ler o primeiro nó.You must call Read to read the first node. O Read método define o estado do leitor de XML para iniciar ReadState.Initial e percorre o arquivo XML sequencialmente até atingir o final do arquivo; nesse ponto, o método retorna um valor de false .The Read method sets the state of the XML reader to initiate ReadState.Initial and moves through the XML file sequentially until it reaches the end of the file, at which point the method returns a value of false.

Esse método requer pelo menos quatro bytes do fluxo de dados para começar a análise.This method requires at least four bytes from the data stream in order to begin parsing. Se menos de quatro bytes forem retornados e não houver mais dados no fluxo, o método retornará false .If fewer than four bytes are returned and there is no more data in the stream, the method returns false. Se houver mais dados no fluxo, o método bloqueará a análise até o recebimento do quarto byte.If there is more data in the stream, the method will block parsing until receipt of the fourth byte.

Para obter a versão assíncrona desse método, consulte ReadAsync .For the asynchronous version of this method, see ReadAsync.

Aplica-se a