在VB.NET中反序列化现有XML文件

时间:2015-11-26 00:08:58

标签: .net xml vb.net xml-serialization

我正在更改VB.NET应用程序以使用XmlSerializer而不是XMLDocument来读取/写入XML设置文件,并希望保持向后兼容性。

以下是XML文件内容的示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <postHistory>
      <postFile>a.txt</postFile>
      <postFile>b.txt</postFile>
      <postFile>c.txt</postFile>
    </postHistory>
  </appSettings>
  <SettingsPath>d.txt</SettingsPath>
</configuration>

以下是我提出的正确反序列化原始文件的类。

Imports System.Xml.Serialization
Imports System.Collections.Generic

<XmlRoot("configuration")>
Public Class LocalSettings
  <XmlElement("appSettings")>
  Public appSettings As New postHistory()
  Public SettingsPath As String = ""
End Class

Public Class postHistory
  Public postHistory As New SubSettings()
End Class

Public Class SubSettings
  <XmlElement("postFile")>
  Public postHistory As New List(Of String)
End Class

这是用于反序列化文件的代码:

  Public Shared Function GetLocalSettings(ByVal filePath As String) As LocalSettings
    Dim lSettings As New LocalSettings()

    Try
      Dim xs As New XmlSerializer(GetType(LocalSettings))
      Using fs As New FileStream(filePath, FileMode.Open)
        lSettings = xs.Deserialize(fs)
      End Using
    Catch ex As Exception
      ' Handle exception
    End Try

    Return lSettings
  End Function

此解决方案有效,但感觉很尴尬。是否有一种更优化的反序列化方法,不需要嵌套“历史记录”&#39;在两个子类中列出?

1 个答案:

答案 0 :(得分:0)

您可以使用XmlArrayAttribute(string name)指定列表应该在两个级别中序列化,外部容器元素具有指定的名称。然后,您可以使用XmlArrayItemAttribute(string name)指定内部元素名称。

因此:

<XmlRoot("configuration")>
Public Class LocalSettings
  <XmlElement("appSettings")>
  Public appSettings As New postHistory()
  Public SettingsPath As String = ""
End Class

Public Class postHistory
  <XmlArray("postHistory")>
  <XmlArrayItem("postFile")>
  Public postHistory As New List(Of String)
End Class

这允许消除SubSettings类。

示例fiddle

有关详细信息,请参阅Controlling XML Serialization Using Attributes