我有一些DataTables
我要导出到xml
文件。我可以使用DataTable.WriteXml()
将DataTables
的内容输出到XML
。
我需要使用Response object
,如图所示。我需要将属性添加到输出xml的根目录。请帮帮我。这是我正在处理的代码。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim FileName1 As String = "Sheet1.xml"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & FileName1)
Response.ContentType = "text/xml"
Dim ds As New DataSet("BuildingGroups")
ds.EnforceConstraints = False
Dim dtBuildingGroup As DataTable = Pipeline.Products.Components.BuildingGroupManager.GetBuildingGroupsToXML
Dim result As String
Dim sw As New StringWriter()
dtBuildingGroup.TableName = "BuildingGroup"
ds.Tables.Add(dtBuildingGroup)
'Dim doc As New XmlDataDocument(ds)
ds.WriteXml(sw)
result = sw.ToString()
Response.Write(result)
Response.End()
End Sub
答案 0 :(得分:2)
您需要从string
获取XML
才能在Response.Write(result)
中使用它,以下是一些方法:
假设一个小DataSet
像这样创建:
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("Column1"))
dt.Columns.Add(New DataColumn("Column2"))
Dim r = dt.NewRow
r.Item(0) = "Value1"
r.Item(1) = "Value2"
dt.Rows.Add(r)
r = dt.NewRow
r.Item(0) = "Value3"
r.Item(1) = "Value4"
dt.Rows.Add(r)
Dim ds As New DataSet
ds.Tables.Add(dt)
您可以使用GetXml
中的DataSet
方法。
Dim simpleresult As String = ds.GetXml
输出:
<NewDataSet>
<Table1>
<Column1>Value1</Column1>
<Column2>Value2</Column2>
</Table1>
<Table1>
<Column1>Value3</Column1>
<Column2>Value4</Column2>
</Table1>
</NewDataSet>
如果您想控制WriteXml
,可以使用DataSet
或DataTable
中的XmlWriteMode
种方法。您使用String
获得MemoryStream
。
Dim result As String
Using ms As New IO.MemoryStream()
ds.WriteXml(ms, System.Data.XmlWriteMode.WriteSchema)
result = System.Text.Encoding.UTF8.GetString(ms.ToArray)
End Using
输出:
<NewDataSet>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Table1">
<xs:complexType>
<xs:sequence>
<xs:element name="Column1" type="xs:string" minOccurs="0" />
<xs:element name="Column2" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<Table1>
<Column1>Value1</Column1>
<Column2>Value2</Column2>
</Table1>
<Table1>
<Column1>Value3</Column1>
<Column2>Value4</Column2>
</Table1>
</NewDataSet>