2014年3月6日 星期四

DATATABLE和XML互相转换

參考引用來源
--


  '''
    ''' DATATABLE转为XML格式的字符串
    '''
    '''
    '''
    '''
    Private Function CreateXmlToString(ByVal dt As DataTable) As String
        Dim settings As New XmlWriterSettings
        settings.Indent = True
        settings.NewLineOnAttributes = True
        Dim strxml As New StringBuilder()
        Dim writer As XmlWriter = XmlWriter.Create(strxml, settings)


        Try
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                writer.WriteStartDocument()
                writer.WriteStartElement("expenditure")
                writer.WriteStartElement("FYDATA")
                writer.WriteAttributeString("name", "费用明细字符串")
                For i As Integer = 0 To dt.Rows.Count - 1
                    writer.WriteStartElement("item")
                    writer.WriteAttributeString("CustomerID", dt.Rows(i).Item("CustomerID"))
                    writer.WriteAttributeString("CompanyName", dt.Rows(i).Item("CompanyName"))
                    writer.WriteAttributeString("ContactName", dt.Rows(i).Item("ContactName"))
                    writer.WriteAttributeString("ContactTitle", dt.Rows(i).Item("ContactTitle"))
                    writer.WriteAttributeString("Address", dt.Rows(i).Item("Address"))
                    writer.WriteEndElement()
                Next
                writer.WriteEndElement()
                writer.WriteEndElement()
                writer.WriteEndDocument()
                writer.Flush()
                writer.Close()
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return strxml.ToString()
    End Function


 '''
    ''' XML格式的字符串转为DATASET
    '''
    '''
    '''
    '''
    Private Function DataToXml(ByVal strxml As String) As DataSet
        Dim result As New DataSet
        Try
            If strxml.Trim.Length > 0 Then
                '读取成流文件
                Dim stream As StringReader = New StringReader(strxml)
                '对xml流文件的只进只读访问
                Dim xread As XmlTextReader = New XmlTextReader(stream)
                '把数据读入DATASET中
                result.ReadXml(xread)
            End If
        Catch ex As Exception
            Throw ex
        End Try
        Return result
    End Function

沒有留言:

張貼留言