0

I have a VB.Net program that processes XML files from a selected folder. The problem is I receive an error if the program gets to an XML file that is not valid because of bad formatting (i.e. no matching end tag). In these cases I would just like to skip that file and move on in the code. Here is where the error occurs and process stops:

XmlDocument.Load(XMLFile)

Does anyone know how I can either test if the file is a valid XML file before loading or I can put an error handle around the loading so my program does not stop if such a file is encountered? Thanks!

Sweez
  • 1
  • 1
    Does this answer your question? [How to validate xml code file though .NET? + How would I do it if I use XML serialization?](https://stackoverflow.com/questions/2111747/how-to-validate-xml-code-file-though-net-how-would-i-do-it-if-i-use-xml-seri) – Trevor Apr 13 '21 at 16:15

1 Answers1

0

You can wrap the load in a Try-Catch.

    For Each XMLFile As String In SelectedFolder
        Try
            Dim xe As XElement = XElement.Load(XMLFile)
            'file is good
        Catch XMLex As Xml.XmlException
            'file is bad
            Stop 'comment/remove to ignore this error
        Catch ex As Exception
            'file is bad
            Stop 'comment/remove to ignore this error
        End Try
    Next
dbasnett
  • 11,334
  • 2
  • 25
  • 33