VB.NET - Find text in XML file

Asked

Viewed 414 times

2

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

I insert the data correctly, but I need to do a validation to not insert repeated files, so I need to check if the text already exists within XML.

My XML file is as follows:

<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 contents of the Name tags already exist.

It is possible to do this?

2 answers

1

First it is necessary to know the following to answer your question:

  • If you have already done the XML file interpreter and,
  • How you’re handling each element.

Assuming you are using a dynamic class, that there are properties Nome and Path, list the XML elements with a ghost list, adding each name to the list.

Below is a pseudo-code, whose done for 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 above code, I have already created the dynamic class for each element in your XML. The item Musica.Nome is added to the ghost list, so it is always checked if the item already exists in the list.


If you haven’t developed code to interpret XML, consider opening a new question, or learn how to read XML files with Visual Basic.

0

The framework already solved this a long time ago. Serialize your class!

Don’t do it procedural, 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. then you can save it locally, for example.

Example of how to do Class -> XML

Browser other questions tagged

You are not signed in. Login or sign up in order to post.