Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
反序列化VB.NET中现有的XML文件_.net_Xml_Vb.net_Xml Serialization - Fatal编程技术网

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

反序列化VB.NET中现有的XML文件,.net,xml,vb.net,xml-serialization,.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>

我正在将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>
这个解决方案有效,但感觉很尴尬。是否有一种更理想的反序列化方法不需要将“postHistory”列表嵌套在两个子类中?

您可以使用该方法指定列表应在两个级别序列化,外部容器元素具有指定的名称。然后可以使用指定内部元素名称

因此:


公共类本地设置
公共应用程序设置作为新的postHistory()
Public SettingsPath As String=“”
末级
公共课后历史
公共postHistory作为新列表(字符串)
末级
这允许取消
子设置

样品


有关更多信息,请参阅。

是什么生成了该XML?它似乎有一个标准app.config文件的布局,直到您看到
appSettings
的内容为止。可能有更好的方法可以做到这一点,但现在我想到的是两件事:1)这是因为XML的布局就是这样,而XMLDeserializer很幼稚,希望基于XML结构创建对象;2)它是有效的,我同意。只有修改xml并删除posthistory标记。感谢您的反馈建议。我想让解决方案尽可能简单,我只是在.NET序列化框架中寻找任何替代方案。这就是我所寻找的语法,谢谢!很好!
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
<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