VB.NET - Find text in XML file

2

I need some help to validate an XML file I'm using as a database.

I do the insertion of the data correctly, however I need to do a validation not to insert repeated files, so I need to check if the text already exists inside the XML.

My XML file looks like this:

<Musicas>
  <Musica>
    <Nome>Musica1</Nome>
    <Path>D:\teste\Musicas\Musica1.txt</Path>
  </Musica>
  <Musica>
    <Nome>Musica2</Nome>
    <Path>D:\teste\Musicas\Musica2.txt</Path>
  </Musica>
</Musicas>

I need to validate if the content of Name tags already exists.

Is it possible to do this?

    
asked by anonymous 08.11.2017 / 19:40

2 answers

1

First you need to know the following to answer your question:

  • If you have already done the XML file interpreter, and
  • How are you dealing with each element.
Assuming you are using a dynamic class, which has the properties Nome and Path , enumerate the XML elements with a phantom list by adding each name in the list.

  

Below is a pseudo-code, which made you understand the algorithm.

Variável ListaFantasma é uma nova Lista (de string)
Sendo XmlElement cada elemento XML no arquivo, faça:
    Se ListaFantasma contém XmlElement -> Nome:
         // Contém o nome, o que fazer agora?
    Caso contrário:
         // Não contém o nome
    Fim do Se
Fim do Sendo

The above pseudo-code in Visual Basic .NET would look something like this:

Public Class MusicaItem
     Public Property Nome As String
     Public Property Path As String
End Class
...
Dim Musicas As New List(Of MusicaItem)

Dim ListaFantasma As New List(Of String)
For Each Musica As MusicaItem In Musicas
    If ListaFantasma.Contains(Musica.Nome) Then
         ' Contém o nome
    Else
         ' Não contém o nome
         ...
         ' Sempre adicione o nome para saber que ele já passou por aqui
         ListaFantasma.Add(Musica.Nome)
    End If
Next

In the code above, I've already created the dynamic class for each element in its XML. The Musica.Nome item is added to the ghost list, so it is always checked if the item already exists in the list.

If you have not developed a code to interpret XML, consider opening a new question, or learn read XML files with Visual Basic .

    
09.11.2017 / 02:34
0

The framework has solved this for some time. Serialize your class!

Do not procedurally, use object orientation in your favor. Theoretically you create a class that reflects your XML, fills it and then serializes it and returns an XML in string format. hence you can save it locally, for example.

Class example - > XML

    
14.11.2017 / 14:15