XML反序列化中的可选元素

时间:2014-11-05 13:38:41

标签: .net xml vb.net serialization

我正在向现有类中的类添加一些属性,我希望将其视为XML反序列化器的可选项。我添加了IsNullable参数以及Specified属性无济于事。我的代码如下所示:

<XmlElement("name")>
Public Property Name As String
<XmlElement("car", IsNullable:=True)>
Public Property Car As String

<XmlIgnore>
Public ReadOnly Property CarSpecified As Boolean
    Get
        Return Car <> String.Empty
    End Get
End Property

XML看起来像:

<?xml version="1.0" encoding="UTF-8" ?>
<Class>
    <name>Test</name>
</Class>

我收到一条例外消息“值不能为空。参数名称:值”

2 个答案:

答案 0 :(得分:1)

您必须提供更多代码。根据您显示的代码,我没有看到问题(这没有错误执行并显示正确的值):

Imports System.Xml.Serialization

Module Module1

   Sub Main()

      Dim xd = _
         <?xml version="1.0" encoding="UTF-8"?>
         <Owner>
            <name>Test</name>
         </Owner>

      Dim xds As New XmlSerializer(GetType(Owner))
      Using xr As New System.IO.StringReader(xd.ToString())
         Dim o = DirectCast(xds.Deserialize(xr), Owner)
         Console.WriteLine("{0} - {1} - {2}", o.Name, o.Car, o.CarSpecified)
      End Using
   End Sub
End Module

Public Class Owner
   <XmlElement("name")>
   Public Property Name As String
   <XmlElement("car", IsNullable:=True)>
   Public Property Car As String

   <XmlIgnore>
   Public ReadOnly Property CarSpecified As Boolean
      Get
         Return Car <> String.Empty
      End Get
   End Property
End Class

答案 1 :(得分:0)

尝试Public Property Car As String? - 问号将确保该属性可以为空。

编辑:尝试以下操作:

Public ReadOnly Property CarSpecified As Boolean
Get
    Return Car isnot nothing
End GetEnd Property