Search code examples
.netxmllinq-to-xmllarge-filesxmlreader

Parse xml in c# : combine xmlreader and linq to xml


I have to parse large XML file in C#. I use LINQ-to-XML. I have a structure like

<root>
       <node></node>
       <node></node>
</root>

I would like use XmlReader to loop on each node and use LINQ-to-XML to get each node and work on it ?

So I have only in memory the current node.


Solution

  • You can do something like that:

    string path = @"E:\tmp\testxml.xml";
    using (var reader = XmlReader.Create(path))
    {
    
        bool isOnNode = reader.ReadToDescendant("node");
        while (isOnNode)
        {
            var element = (XElement)XNode.ReadFrom(reader);
    
            // Use element with Linq to XML
            // ...
    
            isOnNode = reader.ReadToNextSibling("node");
        }
    }