Jak streamovat fragmenty XML ze třídy XmlReader (LINQ to XML)
Pokud potřebujete zpracovat velké soubory XML, nemusí být možné načíst celý strom XML do paměti. Tento článek ukazuje, jak streamovat fragmenty pomocí jazyka XmlReader C# a Visual Basic.
Jedním z nejúčinnějších způsobů, jak použít XmlReader ke čtení XElement objektů, je napsat vlastní metodu osy. Metoda osy obvykle vrací kolekci, například IEnumerable<T> XElement, jak je znázorněno v příkladu v tomto článku. Ve vlastní osové metodě po vytvoření fragmentu XML voláním ReadFrom metody vraťte kolekci pomocí yield return
. To poskytuje sémantiku odloženého spuštění pro vaši vlastní metodu osy.
Když vytvoříte strom XML z objektu XmlReader , XmlReader musí být umístěn na elementu. Metoda ReadFrom se nevrátí, dokud nepřečte značku uzavření elementu.
Pokud chcete vytvořit částečný strom, můžete vytvořit instanci XmlReaderobjektu , umístit čtenáře na uzel, který chcete převést na XElement strom, a pak vytvořit XElement objekt.
Článek Jak streamovat fragmenty XML s přístupem k informacím hlavičky obsahuje informace o streamování složitějšího dokumentu.
Článek Postup provedení streamované transformace velkých dokumentů XML obsahuje příklad použití LINQ to XML k transformaci extrémně velkých dokumentů XML při zachování malé paměti.
Příklad: Vytvoření vlastní metody osy
Tento příklad vytvoří vlastní metodu osy. Můžete ho dotazovat pomocí dotazu LINQ. Vlastní metoda StreamRootChildDoc
osy může číst dokument, který má opakující se Child
prvek.
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
Tento příklad vytvoří následující výstup:
bbb
ccc
Technika použitá v tomto příkladu udržuje malou paměťovou stopu i pro miliony Child
prvků.