Ver Mensaje Individual
  #28  
Antiguo Hace 2 Días
jlmoli_67 jlmoli_67 is offline
Miembro
 
Registrado: feb 2024
Posts: 139
Reputación: 3
jlmoli_67 Va por buen camino
Yo en .net hago esto:


Código:
Private ListaErrores As List(Of String)

  Public Function ValidarXmlContraXsd(ByVal rutaXml As String, ByVal rutaXsd As String) As Boolean
        ListaErrores = New List(Of String)()

     
        Dim settings As New XmlReaderSettings()
        settings.ValidationType = ValidationType.Schema
        settings.ValidationFlags = settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings

       
        Try
            settings.Schemas.Add(Nothing, rutaXsd)
        Catch ex As Exception
            Throw New Exception("Error al cargar el archivo XSD: " & ex.Message)
        End Try

       
        AddHandler settings.ValidationEventHandler, AddressOf CapturarErrorValidacion

       
        Try
            Using reader As XmlReader = XmlReader.Create(rutaXml, settings)
                ' Recorrer todo el XML para forzar la validación completa
                While reader.Read()
                End While
            End Using
        Catch ex As Exception
            ListaErrores.Add("Error de lectura/sintaxis XML: " & ex.Message)
        End Try

      
        If ListaErrores.Count = 0 Then
           ' Console.WriteLine("El archivo XML es VÁLIDO según el XSD.")
            Return True
        Else
           ' Console.WriteLine("Se encontraron " & ListaErrores.Count & " errores de validación:")
            For Each err As String In ListaErrores
                Console.WriteLine("- " & err)
            Next
            Return False
        End If
    End Function
La llamo asi:

Código:
  Dim esValidoXsd As Boolean = ValidarXmlContraXsd("altaFacturas1.xml", Application.StartupPath & "\os-UBL-2.5\xsd\maindoc\UBL-Invoice-2.5.xsd")
       
         If Not esValidoXsd Then
            ' Une todos los errores de la lista en un solo texto separado por saltos de línea para mostrarlos en el MsgBox
            Dim detalleErrores As String = String.Join(Environment.NewLine, ListaErrores)
            MsgBox("El XML no es válido. Errores encontrados:" & Environment.NewLine & detalleErrores, MsgBoxStyle.Critical, "Error de Validación XSD")

           
            Exit Sub
        Else
            MsgBox("El archivo XML es VÁLIDO según el XSD.", MsgBoxStyle.Information)
        End If
el xsd lo baje del fichero comrprimido UBL-2.5.zip que esta en https://docs.oasis-open.org/ubl/os-UBL-2.5/ para una vez descomprimido poder llamar a la ruta local \os-UBL-2.5\xsd\maindoc\UBL-Invoice-2.5.xsd

(El Moderador) Por favor, añadid TAGs al mensaje cuando utilicéis código (Delphi, XML, NET,...)

Última edición por Neftali [Germán.Estévez] fecha: Hace 2 Días a las 17:38:41. Razón: Añadir TAG's al código
Responder Con Cita