Come trasmettere frammenti XML da un oggetto XmlReader (LINQ to XML)
Quando è necessario elaborare file XML di grandi dimensioni, potrebbe risultare impossibile caricare in memoria l'intero albero XML. Questo articolo illustra come trasmettere frammenti usando un oggetto XmlReader in C# e in Visual Basic.
Uno dei modi più efficaci per usare un oggetto XmlReader per leggere oggetti XElement consiste nello scrivere un metodo dell'asse personalizzato. Un metodo dell'asse restituisce in genere una raccolta, ad esempio IEnumerable<T> di XElement, come illustrato nell'esempio di questo articolo. Nel metodo dell'asse personalizzato, dopo avere creato il frammento XML chiamando il metodo ReadFrom, restituire la raccolta usando yield return
. In questo modo si fornisce la semantica di esecuzione posticipata al metodo dell'asse personalizzato.
Quando si crea un albero XML da un oggetto XmlReader, XmlReader deve essere posizionato su un elemento. Il metodo ReadFrom restituisce risultati solo dopo aver letto il tag di chiusura dell'elemento.
Se si desidera creare un albero parziale, è possibile creare un'istanza di XmlReader, posizionare il lettore sul nodo da convertire in un albero XElement e quindi creare l'oggetto XElement.
L'articolo Come trasmettere frammenti XML con accesso alle informazioni di intestazione contiene informazioni sullo streaming di un documento più complesso.
L'articolo Come eseguire la trasformazione del flusso di documenti XML di grandi dimensioni contiene un esempio dell'uso di LINQ to XML per trasformare documenti XML di dimensioni estremamente grandi mantenendo un footprint di memoria ridotto.
Esempio: Creare un metodo dell'asse personalizzato
In questo esempio viene creato un metodo dell'asse personalizzato. È possibile sottoporlo a query tramite una query LINQ. Il metodo dell'asse personalizzato StreamRootChildDoc
può leggere un documento con un elemento Child
ripetuto.
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
Nell'esempio viene prodotto l'output seguente:
bbb
ccc
La tecnica usata in questo esempio mantiene un footprint di memoria ridotto anche per diversi milioni di elementi Child
.