优雅的解决方案:存储XML数据

3

我已经成功让我的应用程序从xml文档中读取一些值,但是我不确定如何存储它们,因为每个元素目前有6个信息需要存储。

XML示例:

<?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>

我在考虑使用一个带有唯一ID的数组,因为我已经为每个应用程序都有一个ID了,但我不知道如何动态创建一个以另一个变量名命名的数组。我尝试使用字典,但是我有超过两个变量,并且不知道如何让它与之配合。

基本上,我需要一种存储所有这些信息的方式,可以无限地添加应用程序,而不使用数据库。


我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
2个回答

3

将您的XML结构更改为树形结构会非常有用,就像这样:

<?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>

然后你可以拥有这个类:
```` class MyClass: ````
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

假设您按名称进行索引,那么您需要一个(字符串,应用程序)字典。

您可以像这样填充它(其中xmlXDocument类型):

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

如果你想减少代码量,可以考虑使用XML序列化技术。以下是一些我通过谷歌搜索找到的例子:

我喜欢你的方法,但是在 For Each elem As XElement In xml.Elements() 这一行遇到了问题。我似乎无法让它工作,可能只是因为现在很晚了,我很累,但无论我尝试什么,都无法让它喜欢那一行。 - crackruckles

1

你只关心在应用程序运行时存储这些数据吗?我会使用一个数据表格。

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

这只是临时存储,因为该应用程序被设计成一次性使用的东西,因此具有动态性。该应用程序从XML文档中读取以创建其UI并确定其需要执行的操作,因此从用户的角度来看,该应用程序只是一次性的东西,但从我的角度来看,它将节省我大量时间,因为我不必再次编写相同的应用程序,只需进行一些微小的更改即可。 - crackruckles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接