VB.NET Working with XML?

Asked

Viewed 220 times

2

I’m filling out a ComboBox from a Xml:

Dim mXml As New XmlDocument
Dim Arquivo As New IO.FileInfo(My.Application.Info.DirectoryPath & "\Configuracao.xml")
mXml.Load(Arquivo.FullName)

Dim SearchMusic As New DataSet
SearchMusic.ReadXml(Arquivo.ToString)
Me.ComboBox_list.DisplayMember = "Nome"
Me.ComboBox_list.DataSource = SearchMusic.Tables(0)
SearchMusic = Nothing

My XML is as follows:

<Musicas>    
  <Musica>    
    <Nome>teste1</Nome>    
    <Path>D:\teste</Path>    
  </Musica>    
  <Musica>    
    <Nome>Teste2</Nome>  
    <Path>c:\</Path>
 </Musica>
 <Musica>    
    <Nome>Tesssste</Nome>    
    <Path>c:\Windows\</Path>    
 </Musica>    
</Musicas>

I need to know how to find the contents of tag Path according to name, example:

  • I write teste1 he needs to call me back D:\teste, it is possible to do this?
  • I have no way to answer right now, but search for xpath.

1 answer

0

Its initial implementation is redundant and fails at some points, for example:

Dim SearchMusic As New DataSet
SearchMusic.ReadXml(My.Application.Info.DirectoryPath & "\Configuracao.xml")
Me.ComboBox_list.DisplayMember = "Nome"
Me.ComboBox_list.DataSource = SearchMusic.Tables(0)

already solves that unnecessary and redundant line pile, of course I’m thinking of your initial code that should be improved.

The search can be done by making a filter in the Datatable by the Select method:

Dim SearchMusic As New DataSet
Dim Nome As String = "teste1"
Dim Result As String = ""

SearchMusic.ReadXml(My.Application.Info.DirectoryPath & "\Configuracao.xml")

Dim Path = SearchMusic _
      .Tables(0) _
      .Select(String.Format("Nome = '{0}'", Nome)) _
      .FirstOrDefault()

If (Not IsNothing(Path)) Then
    Result = Path.Item("Path").ToString() // resultado esperado
End If

Another solution can be made using Xdocument of namespace System.Linq:

Dim doc = XDocument.Parse(IO.File.ReadAllText(My _
          .Application.Info.DirectoryPath & "\Configuracao.xml"))
If (Not IsNothing(doc)) Then
    Dim result = (From a In doc.Descendants("Musica")
     Select New With {.Nome = a.Element("Nome").Value, .Path = a.Element("Path").Value}) _
                       .ToArray()
    Dim Nome As String = "teste1"
    Dim Pesquisa = result.Where(Function(w) w.Nome = Nome).FirstOrDefault()
    If (Not IsNothing(Pesquisa)) Then
        Dim _path = Pesquisa.Path // resultado esperado
    End If
End If

References

Browser other questions tagged

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