See if XML file actually has XML?

poe

Member
Joined
Oct 8, 2006
Messages
12
Programming Experience
Beginner
Hello, I'm making a program, and on start up I have so it searches for XML files in a folder, then add the values from each file to a datagrid. Now my problem is that if an XML file happens to be empty my program can't find the nodes and will then crash.
So how can I make it first check if the file actually has the nodes, and if it doesn't, then just skip it.

Here is my code:
VB.NET:
        Dim files() As String = Directory.GetFiles(Application.StartupPath + "\data\lyrics\", "*.xml")
        Dim rowc As Integer = 0
        For Each FILE_NAME As String In files
            ds.ReadXml(FILE_NAME)
            dg.DataSource = ds
            dg.DataMember = "Song"
            dg.Columns(3).Visible = False
            dg.Columns(4).Visible = False
            dg.Columns(5).Visible = False
            dg.Rows.Item(rowc).Cells.Item(5).Value = FILE_NAME
            rowc += 1
        Next

Thanks.
 
If file is empty you see this with the IO.FileInfo class, Length property would have value 0 if file is empty.

You can also use Try-Catch. The ReadXml method expects a Xml file. An empty file without a root element is not well-formed Xml, it breaks the syntax rules of Xml and is thus not a Xml file. This is an exceptional case where you have designed and coded the application to handle Xml data and does not get such input, so try-catching the exception is valid programming to circumvent this situation.
 
Thanks for you reply! I fixed the problem with the Try-Catch thing like you said. Here is the code if anyone wants to see.

VB.NET:
        Dim files() As String = Directory.GetFiles(Application.StartupPath + "\data\lyrics\", "*.xml")
        Dim rowc As Integer = 0
        Try
            For Each FILE_NAME As String In files
                ds.ReadXml(FILE_NAME)
                dg.DataSource = ds
                dg.DataMember = "Song"
                dg.Columns(3).Visible = False
                dg.Columns(4).Visible = False
                dg.Columns(5).Visible = False
                dg.Rows.Item(rowc).Cells.Item(5).Value = FILE_NAME
                rowc += 1
            Next
        Catch empty As XmlException

        End Try
 
Do the try-catch inside the ForEach loop instead, that way if one of the files errors out the others are still processed.
 
Back
Top