Ir ao conteúdo
  • Cadastre-se

VB.NET - Erro no acesso a arquivo XSD


r.fagioli

Posts recomendados

Olá pessoal

Criei uma aplicação para bricar um pouco com a criação e validação de arquivos XML. Então, criei uma função que valida um arquivo XML baseado em um arquivo XSD. O código dessa função é esse:

       Private Shared Function ValidateXML() As Boolean
Dim ValidatingReader As XmlReader

Dim ReaderSettings As New XmlReaderSettings

Try
CreateXMLSchema()

ValidatingXmlStatus = True

AddHandler ReaderSettings.ValidationEventHandler, AddressOf ReaderSettings_ValidationEventHandler

ReaderSettings.ValidationType = ValidationType.Schema

ReaderSettings.Schemas.Add(Nothing, Application.StartupPath + "\" + strXMLSchemaName)

ValidatingReader = XmlReader.Create(Application.StartupPath + "\" + strXMLName, ReaderSettings)

While ValidatingReader.Read()
End While

Return ValidatingXmlStatus
Catch ex As Exception
MessageBox.Show("Ocorreu uma exceção: " + vbCrLf + vbCrLf + ex.Message, strAppName, MessageBoxButtons.OK, MessageBoxIcon.Error)

Return False
Finally
If File.Exists(Application.StartupPath + "\" + strXMLSchemaName) Then File.Delete(Application.StartupPath + "\" + strXMLSchemaName)

ReaderSettings = Nothing

ValidatingReader = Nothing

GC.Collect()
End Try

A função chama o método CreateXmlSchema que é esse a seguir:

       Private Shared Sub CreateXMLSchema()
Dim NameSpaceManager As New XmlNamespaceManager(New NameTable())

Dim SchemaSet As New XmlSchemaSet

Dim NewSchema As New XmlSchema

Dim CompiledSchema As New XmlSchema

Dim mElement As New XmlSchemaElement()

Dim mElementComplexType As New XmlSchemaComplexType

Dim mElementSequence As New XmlSchemaSequence

Dim sElement(2) As XmlSchemaElement

Dim sElementComplexType(2) As XmlSchemaComplexType

Dim sElementSequence(2) As XmlSchemaSequence

Dim element As New XmlSchemaElement

Dim elementSimpleType As New XmlSchemaSimpleType

Dim elementSimpleTypeRestriction As New XmlSchemaSimpleTypeRestriction

Dim elementMinLenghtFacet As New XmlSchemaMinLengthFacet

Dim elementMaxLenghtFacet As New XmlSchemaMaxLengthFacet

Try
If File.Exists(Application.StartupPath + "\" + strXMLSchemaName) Then File.Delete(Application.StartupPath + "\" + strXMLSchemaName)

elementMinLenghtFacet.Value = 1

elementMaxLenghtFacet.Value = 60

elementSimpleTypeRestriction.BaseTypeName = New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
elementSimpleTypeRestriction.Facets.Add(elementMinLenghtFacet)
elementSimpleTypeRestriction.Facets.Add(elementMaxLenghtFacet)

elementSimpleType.Content = elementSimpleTypeRestriction

element.Name = strXmlNodeChildElementName1
element.MinOccurs = 1
element.MaxOccurs = 1
element.SchemaType = elementSimpleType

sElementSequence(0) = New XmlSchemaSequence
sElementSequence(0).Items.Add(element)

sElementComplexType(0) = New XmlSchemaComplexType
sElementComplexType(0).Particle = sElementSequence(0)

sElement(0) = New XmlSchemaElement
sElement(0).Name = strXmlNodeChildName1
sElement(0).MinOccurs = 0
sElement(0).MaxOccurs = 1
sElement(0).SchemaType = sElementComplexType(0)

sElementSequence(1) = New XmlSchemaSequence
sElementSequence(1).Items.Add(element)

sElementComplexType(1) = New XmlSchemaComplexType
sElementComplexType(1).Particle = sElementSequence(1)

sElement(1) = New XmlSchemaElement
sElement(1).Name = strXmlNodeChildName2
sElement(1).MinOccurs = 0
sElement(1).MaxOccurs = 1
sElement(1).SchemaType = sElementComplexType(1)

sElementSequence(2) = New XmlSchemaSequence
sElementSequence(2).Items.Add(element)

sElementComplexType(2) = New XmlSchemaComplexType
sElementComplexType(2).Particle = sElementSequence(2)

sElement(2) = New XmlSchemaElement
sElement(2).Name = strXmlNodeChildName3
sElement(2).MinOccurs = 0
sElement(2).MaxOccurs = 1
sElement(2).SchemaType = sElementComplexType(2)

mElementSequence.Items.Add(sElement(0))
mElementSequence.Items.Add(sElement(1))
mElementSequence.Items.Add(sElement(2))

mElementComplexType.Particle = mElementSequence

mElement.Name = strXmlNodeName
mElement.SchemaType = mElementComplexType

NewSchema.AttributeFormDefault = XmlSchemaForm.Qualified
NewSchema.ElementFormDefault = XmlSchemaForm.Qualified
NewSchema.Items.Add(mElement)

NameSpaceManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema")

AddHandler SchemaSet.ValidationEventHandler, AddressOf SchemaSet_ValidationCallbackOne

SchemaSet.Add(NewSchema)
SchemaSet.Compile()

For Each TempSchema As XmlSchema In SchemaSet.Schemas()
CompiledSchema = TempSchema
Next

CompiledSchema.Write(File.Create(Application.StartupPath + "\" + strXMLSchemaName), NameSpaceManager)
Catch ex As Exception
MessageBox.Show("Ocorreu uma exceção: " + vbCrLf + vbCrLf + ex.Message, strAppName, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
elementMinLenghtFacet = Nothing

elementMaxLenghtFacet = Nothing

elementSimpleTypeRestriction = Nothing

elementSimpleType = Nothing

element = Nothing

sElementSequence(0) = Nothing
sElementSequence(1) = Nothing
sElementSequence(2) = Nothing

sElementComplexType(0) = Nothing
sElementComplexType(1) = Nothing
sElementComplexType(2) = Nothing

sElement(0) = Nothing
sElement(1) = Nothing
sElement(2) = Nothing

mElementSequence = Nothing

mElementComplexType = Nothing

mElement = Nothing

CompiledSchema = Nothing

NewSchema = Nothing

SchemaSet = Nothing

NameSpaceManager = Nothing

GC.Collect()
End Try
End Sub

Depois de criado o arquivo XSD, eu não consigo acessá-lo, pois é informado que o arquivo em questão está sendo usado por outro processo.

O que eu posso fazer para resolver esse problema?

Obrigado

Link para o comentário
Compartilhar em outros sites

  • Membro VIP

Dica 1: Organize melhor/limpe seu código, tem variáveis demais, arrays desnecessárias, variáveis declaradas com "As New" e depois instanciadas de novo e um "For Each" sobrando, com o código mais limpo fica mais fácil de achar os problemas.

Dica 2: Substitua todos os File.funcao por uma instância do FileInfo e chame as funções a partir dele, no fim use essa instância para certificar-se de que o arquivo foi fechado.

Link para o comentário
Compartilhar em outros sites

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

Ebook grátis: Aprenda a ler resistores e capacitores!

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!