VB.NET - XMLSerialization - 添加'数组的Type属性'到Array的根节点

时间:2017-05-16 13:13:58

标签: xml vb.net serialization

我对Classes进行了以下设置,以使用vb.net使用序列化创建一些XML。

Public Class USER
    Public Property USERCODE As String
    Public Property COMPANYCODE As String
    Public Property LEDGERCODE As String
    Public Property WORKGROUP As String
    Public Property SYSTEMDATE As Date
End Class

Public Class JOB
    Private myItems() As Object
    Public Property USER As New SchedulerParameters.USER
    Public Property [OBJECT] As String
    Public Property METHOD As String

    <XmlArrayItem(ElementName:="PARAMETER"), XmlArray()>
    Public Property PARAMETERS As Object()
        Get

            Return myItems
        End Get
        Set
            myItems = Value
        End Set
    End Property
End Class

创建

<JOB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    
<USER>      
    <USERCODE>RW</USERCODE>      
    <COMPANYCODE>DEM</COMPANYCODE>      
    <LEDGERCODE>PL1</LEDGERCODE>      
    <WORKGROUP>DIRECTOR</WORKGROUP>      
    <SYSTEMDATE>0001-01-01T00:00:00</SYSTEMDATE>    
</USER>    
<OBJECT>QLHSGPostingRoutines.HPM.OrderStatusChange</OBJECT>    
<METHOD>Issue</METHOD>    
<PARAMETERS>
    <PARAMETER xsi:type="xsd:string">66827</PARAMETER>
    <PARAMETER xsi:type="xsd:string">NULL</PARAMETER>
</PARAMETERS>
</JOB>

我想在PARAMETERS上有属性:

<PARAMETERS type="Array">

我打电话使用:

    .....
    _xml.PARAMETERS = _paramArray

    Dim xs As New XmlSerializer(_xml.GetType)

    xs.Serialize(_s, _xml)

    Return _s.ToString

我希望使用但是由于某种原因这不起作用。

如果有人可以帮助我,那就太好了。

感谢。

1 个答案:

答案 0 :(得分:1)

为了做你想做的事情你不能使用这样的简单数组,你 为它创建某种对象/ POCO。

Public Class JOB
    Public Property USER As New SchedulerParameters.USER
    Public Property [OBJECT] As String
    Public Property METHOD As String

    Public Property PARAMETERS As PARAMETERS
End Class

Public Class PARAMETERS
    <XmlAttribute("type")>
    Public Property Type As String = "Array"

    <XmlElement("PARAMETER")>
    Public Property Items As Object()
End Class

通过创建一个类,然后在字符串上指定XmlElement("PARAMETER")XmlAttribute("type"),它将生成您想要的XML:

  <PARAMETERS type="Array">
    <PARAMETER xsi:type="xsd:string">66827</PARAMETER>
    <PARAMETER xsi:type="xsd:string">NULL</PARAMETER>
  </PARAMETERS>

我不确定为什么你想要这种格式,如果你使用.NET来序列化和反序列化它,那么你不要需要额外type属性。