An elegant solution for storing XML data

I have my application to read in some values ​​from my xml document, however I am not sure how I am going to store them as I have a total of 6 pieces of information for each element in the file at the moment.

XML example

<?xml version="1.0" encoding="utf-8"?>
<App>
 <Name>First Application </Name>
 <FileName>1.exe</FileName>
 <FilePath>C:\</FilePath>
 <Third_Parameter>etc</Third_Parameter>
 <Forth_Parameter>etc</Forth_Parameter>
 <Name>Application 2</Name>
 <FilePath></FilePath>
 <Third_Parameter>etc</Third_Parameter>
 <Forth_Parameter>etc</Forth_Parameter>
</App>

      

I was thinking of an array with a unique ID, since I already have one for each application, but I don't know how to dynamically create an array with a different variable name. I've looked at using a dictionary, but I have more than two variables and I don't know how to make it work with that.

Basically I want a way to store all this information for a potentially infinite number of applications without using a database.

+3


source to share


2 answers


It would be helpful to change the XML structure to a tree, for example:

<?xml version="1.0" encoding="utf-8"?>
<Apps>
  <App Name="First Application">
    <FileName>1.exe</FileName>
    <FilePath>C:\</FilePath>
    <Third_Parameter>etc</Third_Parameter>
    <Forth_Parameter>etc</Forth_Parameter>
  </App>
  <App Name="Application 2">
    <FilePath></FilePath>
    <Third_Parameter>etc</Third_Parameter>
    <Forth_Parameter>etc</Forth_Parameter>
  </App>
</Apps>

      

Then you can have this class:

Class App
  Public FileName As String
  Public FilePath As String
  Public Third_Parameter As String
  Public Forth_Parameter As String
  Public AppName As String
End Class

      

And a dictionary (String, App) - it assumes you are indexing by name.



You can fill it like this (where xml

type XDocument

):

Dim dict As New Dictionary(Of String, App)
For Each elem As XElement In xml.Elements()
  Dim app As New App 'each element would be App
  With app
    .AppName = elem.Attribute("Name").Value
    .FileName = elem.Element("FileName").Value
    .FilePath = elem.Element("FilePath").Value
    .Third_Parameter = elem.Element("Third_Parameter").Value
    .Forth_Parameter = elem.Element("Forth_Parameter").Value
  End With
  dict.Add(app.AppName, app)
Next

      

If you want less code, consider XML serialization. Some examples I found on googling:

+2


source


You just need to store this data while the application is running I would use datatable



Dim x As New DataTable
        x.ReadXml("c:\pathtoxml.xml")
        x.AcceptChanges()

      

+1


source







All Articles