XNode.ReadFrom(XmlReader) Metodo

Definizione

Crea un oggetto XNode da un oggetto XmlReader.

public:
 static System::Xml::Linq::XNode ^ ReadFrom(System::Xml::XmlReader ^ reader);
public static System.Xml.Linq.XNode ReadFrom(System.Xml.XmlReader reader);
static member ReadFrom : System.Xml.XmlReader -> System.Xml.Linq.XNode
Public Shared Function ReadFrom (reader As XmlReader) As XNode

Parametri

reader
XmlReader

Oggetto XmlReader posizionato nel nodo da leggere in questo XNodeoggetto .

Valori restituiti

Oggetto XNode contenente il nodo e i relativi nodi discendenti letti dal lettore. Il tipo di runtime del nodo è determinato dal tipo di nodo (NodeType) del primo nodo rilevato nel lettore.

Eccezioni

Non XmlReader è posizionato su un tipo di nodo riconosciuto.

L'oggetto sottostante XmlReader genera un'eccezione.

Esempio

In questo esempio viene usato il file XML seguente, denominato Source.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Root>
  <Child Key="01">
    <GrandChild>aaa</GrandChild>
  </Child>
  <Child Key="02">
    <GrandChild>bbb</GrandChild>
  </Child>
  <Child Key="03">
    <GrandChild>ccc</GrandChild>
  </Child>
</Root>

Nell'esempio seguente viene creato un metodo dell'asse personalizzato che usa ReadFrom e quindi esegue query sull'asse personalizzato usando una query LINQ:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

class Program
{
    static IEnumerable<XElement> StreamRootChildDoc(string uri)
    {
        using (XmlReader reader = XmlReader.Create(uri))
        {
            reader.MoveToContent();
            
            // Parse the file and return each of the nodes.
            while (!reader.EOF)
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Child")
                {
                    XElement el = XElement.ReadFrom(reader) as XElement;
                    if (el != null)
                        yield return el;
                }
                else
                {
                    reader.Read();
                }
            }
        }
    }

    static void Main(string[] args)
    {
        IEnumerable<string> grandChildData =
            from el in StreamRootChildDoc("Source.xml")
            where (int)el.Attribute("Key") > 1
            select (string)el.Element("GrandChild");

        foreach (string str in grandChildData)
            Console.WriteLine(str);
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml
Imports System.Xml.Linq

Module Program
    Iterator Function StreamRootChildDoc(ByVal uri As String) As IEnumerable(Of XElement)

        Using reader As XmlReader = XmlReader.Create(uri)
            reader.MoveToContent()

            ' Parse the file and return each of the nodes.
            While Not reader.EOF

                If reader.NodeType = XmlNodeType.Element AndAlso reader.Name = "Child" Then
                    Dim el As XElement = TryCast(XElement.ReadFrom(reader), XElement)
                    If el IsNot Nothing Then Yield el
                Else
                    reader.Read()
                End If
            End While
        End Using
    End Function

    Sub Main(args As String())

        Dim grandChildData As IEnumerable(Of String) =
            From el In StreamRootChildDoc("Source.xml")
            Where CInt(el.Attribute("Key")) > 1
            Select CStr(el.Element("GrandChild"))

        For Each str As String In grandChildData
            Console.WriteLine(str)
        Next

    End Sub

End Module

In questo esempio viene generato l'output seguente:

bbb
ccc

Commenti

È possibile usare questo metodo per scrivere un metodo che restituisce una raccolta di nodi, producendo ogni nodo mentre il nodo viene letto dal lettore. Questo metodo consente di elaborare file XML arbitrariamente di grandi dimensioni con un footprint di memoria molto ridotto.

Il lettore passato a questo metodo potrebbe generare eccezioni. ReadFrom non rileva tutte le eccezioni generate dal lettore; le eccezioni non gestite vengono visualizzate nel codice che ha chiamato ReadFrom. In particolare, il codice deve essere preparato per gestire XmlException.

Per un esempio di come trasmettere un documento più complesso, vedere Come trasmettere frammenti XML con accesso alle informazioni sull'intestazione.

Alcuni operatori di query standard, ad esempio OrderBy, eseguono l'iterazione dell'origine, raccolgono tutti i dati, lo ordinano e infine producono il primo elemento nella sequenza. Se si usa un operatore di query che materializza l'origine prima di restituire il primo elemento, non si manterrà un footprint di memoria ridotto.

Per un esempio di utilizzo di LINQ to XML per trasformare documenti XML di dimensioni estremamente grandi mantenendo un footprint di memoria ridotto, vedere Come eseguire la trasformazione in streaming di documenti XML di grandi dimensioni.

Si applica a

Vedi anche