1

好的,我在尝试将一段代码序列化为 XML 时遇到了一些问题。我需要 XML 出来这样的东西:

<document DataObject="Y">
   <data Attribute="Y"><![CDATA[01/01/2013]]></data>
</document>

我可以使用 CData 标记生成 xml,但我无法确定元素上的属性。

这是该类的示例:

Public Class document
<XmlAttribute()> _
Public AMSDataObject As String = "Y"

Private _Data As DateTime

<XmlIgnore()> _
Public Property VarData
    Get
        Return _Data
    End Get
    Set(value)
        _Data = value
    End Set
End Property

Public Property Data As XmlCDataSection
    Get
        Return GetCData(Me._Data)
    End Get
    Set(ByVal value As XmlCDataSection)
        Me._Data = value.Value
    End Set
End Property
Private Function GetCData(ByVal value As String) As XmlCDataSection
    Static doc As New XmlDataDocument()
    Static cdata As XmlCDataSection = doc.CreateCDataSection(value)

    Return (cdata)
End Function
End Class

有什么建议么。我确信有一种更简单的方法来处理所有这些。

另外,这里是序列化类。

    Private Sub WriteXMLToFile(ByRef file As AMS_DOC_XML_EXPORT_FILE, ByVal filename As String)
    Dim ser As New XmlSerializer(GetType(AMS_DOC_XML_EXPORT_FILE))
    Dim writer As New StreamWriter(filename)

    'Remove Default name spaces
    Dim xns As New XmlSerializerNamespaces
    xns.Add(String.Empty, String.Empty)

    'Remove XML Declaration in front of file
    Dim xmlsettings As New XmlWriterSettings
    xmlsettings.OmitXmlDeclaration = True
    xmlsettings.Indent = True


    Using xmlwriter As XmlWriter = xmlwriter.Create(writer, xmlsettings)
        ser.Serialize(xmlwriter, file, xns)
    End Using

    writer.Close()
End Sub

谢谢

4

1 回答 1

0

您可以这样做来获取属性,但实际上并不简单:

Public Class document
    <XmlAttribute()> _
    Public AMSDataObject As String = "Y"

    Private _Data As DateTime
    Private _DateData As DateDataElement

    <XmlIgnore()> _
    Public Property VarData As Date
        Get
            Return _Data
        End Get
        Set(value As Date)
            _Data = value
        End Set
    End Property

    <XmlElement()>
    Public Property Data As DateDataElement
        Get
            Return New DateDataElement(_Data)
        End Get
        Set(ByVal value As DateDataElement)
            Me._DateData = value
        End Set
    End Property
End Class

Public Class DateDataElement
    <XmlAttribute()>
    Public Attribute As String = "Y"


    Private _date As DateTime

    Sub New()

    End Sub
    Sub New(dateValue As DateTime)
        _date = dateValue
    End Sub

    <XmlText()>
    Public Property Value As XmlNode()
        Get
            Return New XmlNode() {New System.Xml.XmlDocument().CreateCDataSection(_date.ToString("MM/dd/yyyy"))}
        End Get
        Set(value As XmlNode())
            _date = CDate(value(0).Value) '??
        End Set
    End Property

End Class
于 2013-10-24T23:06:26.083 回答