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

标签 xml vb.net storing-data dynamic-variables

我已经让我的应用程序从我的 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 的数组,因为无论如何我已经为每个应用程序创建了一个,但我不知道如何动态创建一个具有另一个变量名称的数组。我查看了使用字典,但是我有两个以上的变量,不知道如何使用它。

基本上,我需要一种方法来为可能无限量的应用程序存储所有这些信息,而无需使用数据库。

最佳答案

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

还有一个 (String,App) 的字典 - 假设您将按名称进行索引。

您可以像这样填充它(其中 xml 类型为 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

如果您想要更少的代码,请考虑研究 XML 序列化。我通过谷歌搜索找到的一些示例:

关于xml - 存储 XML 数据的优雅解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921255/

相关文章:

c# - 文件不显示在资源管理器中,但 VB.NET 打开它

c++ - 将数据存储在文件中 (C++)

java - weblogic.xml : cvc-complex-type. 2.4.a 中的错误:发现以元素 'prefer-application-packages' 开头的无效内容

java - 制作 Spinner 下拉菜单以匹配屏幕宽度

c# - 在 C# Web 应用程序中访问内容文件

vb.net - 隐藏左列DataGridView

vb.net - FormulaR1C1 不适用于 SUMME

python - OSM 到有向图 (python-igraph/networkx)

mysql - 存储网络分析数据