我需要将数据集导出到xml文件。为此,我尝试下一个示例代码:
Dim dt As DataTable = New DataTable()
dt.TableName ="Test"
Dim dc As DataColumn = New DataColumn("Name", GetType(String))
dc.Caption = "ColumnCaption1"
dt.Columns.Add(dc)
Dim nr As DataRow = dt.NewRow()
nr("Name") = "TestRow"
dt.Rows.Add(nr)
Dim Xml As System.Xml.XmlDocument = New System.Xml.XmlDocument()
Dim RootNode As System.Xml.XmlNode = Xml.CreateElement("Export")
Xml.AppendChild(RootNode)
Dim DocsNode As System.Xml.XmlNode = Xml.CreateElement("Documents")
RootNode.AppendChild(DocsNode)
Dim DocDataSet As DataSet = New DataSet("Doc1")
DocDataSet.Tables.Add(dt)
DocDataSet.EnforceConstraints = False
Dim XmlDoc As System.Xml.XmlDataDocument = New System.Xml.XmlDataDocument(DocDataSet)
Dim DocElement As System.Xml.XmlNode = Xml.ImportNode(XmlDoc.DocumentElement, True)
'DocElement.
DocsNode.AppendChild(DocElement)
Dim Settings As System.Xml.XmlWriterSettings = New System.Xml.XmlWriterSettings()
Settings.Encoding = System.Text.Encoding.UTF8
Settings.Indent = True
Settings.IndentChars = Chr(9)
Settings.CloseOutput = True
Settings.OmitXmlDeclaration = true
Dim DirectoryName as string = "C:\Temp"
Dim FileName As String = DirectoryName & "\myExport"
Dim OutStream As System.IO.FileStream = System.IO.File.Create(FileName)
Dim Writer As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(OutStream, Settings)
Xml.WriteTo(Writer)
Writer.Close()
它有效,导出的结果是:
<Export>
<Documents>
<Doc1>
<Test>
<Name>TestRow</Name>
</Test>
</Doc1>
</Documents>
</Export>
但是我希望列标题(ColumnCaption1)也会在这个xml中。我怎么能这样做?