Partager via


Comment diffuser en continu des fragments XML à partir d’un XmlReader (LINQ to XML)

Lorsque vous devez traiter de grands fichiers XML, il peut être impossible de charger l’intégralité de l’arborescence XML en mémoire. Cet article explique comment diffuser en continu des fragments à l’aide d’un XmlReader dans C# et Visual Basic.

L'une des manières les plus efficaces d'utiliser un objet XmlReader pour lire des objets XElement consiste à écrire votre propre méthode d'axe personnalisée. Une méthode d’axe retourne généralement une collection telle que IEnumerable<T> de XElement, comme illustré dans l’exemple de cet article. Dans la méthode d'axe personnalisée, après avoir créé le fragment XML en appelant la méthode ReadFrom, retournez la collection à l'aide de yield return. Cela fournit une sémantique d'exécution différée à votre méthode d'axe personnalisée.

Lorsque vous créez une arborescence XML à partir d'un objet XmlReader, l'objet XmlReader doit être positionné sur un élément. La méthode ReadFrom ne retourne pas tant qu’elle n’a pas lu la balise de fermeture de l’élément.

Si vous souhaitez créer une arborescence partielle, vous pouvez instancier un objet XmlReader, positionner le lecteur sur le nœud que vous souhaitez convertir en une arborescence XElement, puis créer l'objet XElement.

L’article Comment diffuser en continu des fragments XML avec accès aux informations d’en-tête contient des informations sur la diffusion en continu d’un document plus complexe.

L’article Comment effectuer une transformation en continu de documents XML volumineux contient un exemple d’utilisation de LINQ to XML pour transformer des documents XML extrêmement volumineux tout en conservant une petite empreinte mémoire.

Exemple : Créer une méthode d’axe personnalisée

Cet exemple crée une méthode d'axe personnalisée. Vous pouvez l’interroger à l’aide d’une requête LINQ. La méthode d’axe personnalisée StreamRootChildDoc peut lire un document qui a un élément Child répétitif.

using System.Xml;
using System.Xml.Linq;

static IEnumerable<XElement> StreamRootChildDoc(StringReader stringReader)
{
    using XmlReader reader = XmlReader.Create(stringReader);

    reader.MoveToContent();

    // Parse the file and display each of the nodes.
    while (true)
    {
        // If the current node is an element and named "Child"
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "Child")
        {
            // Get the current node and advance the reader to the next
            if (XNode.ReadFrom(reader) is XElement el)
                yield return el;

        }
        else if (!reader.Read())
            break;
    }
}

string markup = """
                <Root>
                  <Child Key="01">
                    <GrandChild>aaa</GrandChild>
                  </Child>
                  <Child Key="02">
                    <GrandChild>bbb</GrandChild>
                  </Child>
                  <Child Key="03">
                    <GrandChild>ccc</GrandChild>
                  </Child>
                </Root>
                """;

IEnumerable<string> grandChildData =
    from el in StreamRootChildDoc(new StringReader(markup))
    where (int)el.Attribute("Key") > 1
    select (string)el.Element("GrandChild");

foreach (string str in grandChildData)
    Console.WriteLine(str);
Imports System.Xml

Module Module1

    Public Iterator Function StreamRootChildDoc(stringReader As IO.StringReader) As IEnumerable(Of XElement)
        Using reader As XmlReader = XmlReader.Create(stringReader)
            reader.MoveToContent()

            ' Parse the file and display each of the nodes.
            While True

                ' If the current node is an element and named "Child"
                If reader.NodeType = XmlNodeType.Element And reader.Name = "Child" Then

                    ' Get the current node and advance the reader to the next
                    Dim el As XElement = TryCast(XNode.ReadFrom(reader), XElement)

                    If (el IsNot Nothing) Then
                        Yield el
                    End If

                ElseIf Not reader.Read() Then
                    Exit While
                End If

            End While
        End Using
    End Function

    Sub Main()

        Dim markup = "<Root>
                       <Child Key=""01"">
                         <GrandChild>aaa</GrandChild>
                       </Child>
                       <Child Key=""02"">
                         <GrandChild>bbb</GrandChild>
                       </Child>
                       <Child Key=""03"">
                         <GrandChild>ccc</GrandChild>
                       </Child>
                     </Root>"

        Dim grandChildData =
             From el In StreamRootChildDoc(New IO.StringReader(markup))
             Where CInt(el.@Key) > 1
             Select el.<GrandChild>.Value

        For Each s In grandChildData
            Console.WriteLine(s)
        Next

    End Sub
End Module

Cet exemple produit la sortie suivante :

bbb
ccc

La technique utilisée dans cet exemple conserve une petite empreinte mémoire même pour des millions d’éléments Child.

Voir aussi