我已经使用.Net中的XmlSerializer成功地反序列化了我的xml文件,但是尝试将该数据序列化回xml文件变得令人沮丧。当我尝试序列化我的类时,我只获得没有子元素的xml的根标记。如何序列化所有对象以获取带有数据的正确xml?我已经看到有人建议在集合中添加要序列化的类然后序列化该集合但我无法解决这个问题,或者有更简单的方法吗?任何帮助表示赞赏!这是我的代码:
Public Shared Function SerializeXml() As Byte()
Dim serializer As New XmlSerializer(GetType(Data))
Dim nameSpaces As XmlSerializerNamespaces = New XmlSerializerNamespaces()
Dim mStream As New MemoryStream()
Dim result As Byte()
Dim target As New Data()
nameSpaces.Add(String.Empty, String.Empty)
serializer.Serialize(mStream, target, nameSpaces)
result = mStream.ToArray()
Return result
以下是带有属性的xml的通用示例:
<?xml version"1.0">
<RootTag>
<ChildTag Label="Label1" Value="Value1"/>
<ChildTag Label="Label2" Value="Value2"/>
</RootTag>
编辑:这是我的数据类:
Imports System.Xml.Serialization
<XmlRoot("DATA", [Namespace]:="", IsNullable:=False)>
Public Class Data
Inherits Model
<XmlElement("CONFIGURATION")>
Public Property Configuration() As DataConfiguration
Get
Return Me._Configuration
End Get
Set(value As DataConfiguration)
Me._Configuration = value
End Set
End Property
Private _Configuration As DataConfiguration
<XmlElement("FIELD")>
Public Property Field() As Field
Get
Return Me._Field
End Get
Set(value As Field)
Me._Field = value
End Set
End Property
Private _Field As Field
<XmlElement("LIST")>
Public Property ListRoot() As List(Of ListRoot)
Get
Return Me._ListRoot
End Get
Set(value As List(Of ListRoot))
Me._ListRoot = value
End Set
End Property
Private _ListRoot As List(Of ListRoot)
End Class
答案 0 :(得分:0)
这是您的问题,<XmlRoot("DATA", [Namespace]:="", IsNullable:=False)>
。 IsNullable属性设置为false时,如果项目等于空,则将省略项目的XML。如果将IsNullable
设置为True,则会发出类似此<ListRoot xsi:nil = "true" />
的标记。在您的代码示例中,由于您刚刚创建了一个类似Data
的新Dim target As New Data()
类,因此默认情况下所有成员都为Nothing
。由于您已设置IsNullable = False
,因此您应该只看到根标记,这将是数据的有效序列化。