带有CData标记和属性的.NET XML序列化

时间:2013-10-24 15:29:24

标签: .net xml vb.net cdata

好的,我在尝试将一段代码序列化为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

任何建议。我相信有一种更简单的方法可以解决所有这些问题。

此外,这是serlization类。

    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

感谢

1 个答案:

答案 0 :(得分: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