Access

Función VBA para determinar si un archivo es un archivo XML válido

Estaba revisando rápidamente un par de foros para buscar preguntas interesantes, ideas para publicaciones de blog y encontré la siguiente pregunta sobre UA:

Y pensé que esto podría ser una buena publicación rápida.

No hace mucho tiempo, escribí un artículo sobre cómo ‘la mayoría’ los archivos poseen una firma de archivo binario que podemos usar para identificar realmente el tipo de archivo sin confiar en la extensión del archivo:

Lamentablemente, los archivos XML no poseen tal firma, lo que significa que necesitaba encontrar otro enfoque.

Después de algunas pruebas rápidas, creo que la solución más simple es intentar cargar el archivo XML. Entonces, se me ocurrió una rutina muy simple:

'---------------------------------------------------------------------------------------
' Procedure : XML_IsValidFile
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : 
' Purpose   : Determine if a file is a valid XML file.
'             Inspired from the question: 
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - 
' Req'd Refs: Late Binding  -> None required
'             If you wish to switch to Early Binding, then:
'             Microsoft XML, v3.0         -> Use MSXML2.DOMDocument
'             Other versions (e.g., v4.0) -> Use MSXML2.DOMDocument40
'             Microsoft XML, v6.0         -> Use MSXML2.DOMDocument60
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     : Fully qualified path and filename to validate
'
' Output Variables:
' ~~~~~~~~~~~~~~~~~
' Boolean:  True    -> Is a valid XML File
'           False   -> Is NOT a valid XML File
'
' Usage:
' ~~~~~~
' ? XML_IsValidFile("C:\Users\Daniel\Downloads\note.xml")
'   Returns -> True/False
'
' ? XML_IsValidFile("C:\Temp.txt")
'   Returns -> True/False
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2025-04-20              Initial Release
'---------------------------------------------------------------------------------------
Function XML_IsValidFile(sFile As String) As Boolean
    On Error GoTo Error_Handler
    #Const MSXML_EarlyBind = False    'True => Early Binding / False => Late Binding

    #If MSXML_EarlyBind = True Then    'Req'd Ref: Microsoft XML, v3.0
        Dim oDOMDocument      As MSXML2.DOMDocument

        Set oDOMDocument = New MSXML2.DOMDocument
    #Else
        Dim oDOMDocument      As Object

        Set oDOMDocument = CreateObject("MSXML2.DOMDocument")
    #End If

    ' Minimal file validation
    If Dir(sFile) = "" Then Exit Function    ' File does not exist

    With oDOMDocument
        .async = False
        .validateOnParse = False

        If .Load(sFile) Then
            XML_IsValidFile = True

            '        ' Optionally, check for presence of root element ??? for properly formatted file
            '        '     probably a good idea!
            '        If Not .DocumentElement Is Nothing Then
            '            XML_IsValidFile = True
            '        End If

'        ' If you want to see why it can't be loaded. Why it isn't a valid XML file
'        Else
'            Debug.Print "Error Code: " & .parseError.errorCode & vbCrLf & _
'                        "Reason: " & .parseError.reason & _
'                        "Line: " & .parseError.Line & ", Position: " & .parseError.linepos & vbCrLf & _
'                        "Source: " & .parseError.srcText
        End If
    End With

Error_Handler_Exit:
    On Error Resume Next
    Set oDOMDocument = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: XML_IsValidFile" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Entonces puede validar cualquier archivo simplemente haciendo:

If Not XML_IsValidFile("C:\Users\Daniel\Downloads\note.xml") Then
   ' Not an XML dile
End If

' Continue because the XML file was valid

Y eso es todo. Es así de simple.

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba