Search code examples
xmlvb.netmergearray-merge

vb.net console app merge unknown number of XML files, problems adding to collection


I am trying to create an app that allows the user to drag/drop files into a console. The console feeds the paths through a mediator into a collection of XmlTextReaders which in turn fill up a DataSet collection in a for loop based on an XmlReader collection .count and finally merge the whole thing. Well everything is nice and dandy until I try to .add to XmlTextReader list, then it throws a NullReferenceException in the form of error report from vbstudio

I've tried to investigate but just don't get it. The code below has, I hope, all the necessary information.

Imports System.Xml
Module Module1

    Sub Main()
        Dim input As String
        Dim nl As String = Environment.NewLine
        Dim xml_files As List(Of XmlTextReader)
        Dim xml_ds As List(Of DataSet)
        Dim ds_sum As DataSet

        Do While input <> "merge"
            Console.WriteLine("--- drag & drop file to  be merged---" + nl)
            input = Console.ReadLine()
            If input <> "merge" Then 
                Dim xml__ As New XmlTextReader(input)
                xml_files.Add(xml__) ' this is th plce that throws the exception 
                'xml_files.Add(New XmlTextReader(input))  something i tried
                Console.WriteLine(nl & "--- drag & drop new file or order  merge ---" & nl)
            ElseIf input = "merge" Then
                ' ▼ ▼ ▼ ▼  read datasets to collection ▼ ▼ ▼ ▼
                For i = 0 To xml_files.Count - 1
                    Dim ds As New DataSet ' mediator
                    ds.ReadXml(xml_files(i)) ' read one-by-one xml 
                    xml_ds.Add(ds) 'i ubacuje u kolekciju xml_ds
                Next
            End If
        Loop
        ' ▼ ▼ ▼ ▼ ovde sad ide XML MERGE ▼ ▼ ▼ ▼
        ds_sum = xml_ds(0)

        For i = 1 To xml_ds.Count
            ds_sum.Merge(xml_ds(i))
        Next
        ' ▼ ▼ ▼ ▼ ispis xml-a ▼ ▼ ▼ ▼
        Console.WriteLine(nl & "--- direktorijum u koji zelis da sacuvas sabrani XML Prevuci u terminal ---" & nl)
        input = Console.ReadLine()
        ds_sum.WriteXml(input)
    End Sub
End Module

`


Solution

  • Dim xml_files As List(Of XmlTextReader)
    

    only declares xml_files as an object that can contain objects that are lists of XmlTextReaders. It doesn't initialize it. In longhand you would type

    Dim xml_files As List(Of XmlTextReader) = New List(Of XmlTextReader)
    

    which declares the object and assigns to it a new initialized list, but you can write

    Dim xml_files As New List(Of XmlTextReader)
    

    which accomplishes exactly the same thing.