Reputation: 31
I have some DataTables
that I want to export to a xml
file. I can use DataTable.WriteXml()
to output the contents of the DataTables
to XML
.
I need to use a Response object
as shown. I need to add attributes to the root of the output xml. Please help me with that. here is the code which I'm working on.
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
Upvotes: 3
Views: 29384
Reputation: 8647
You need to get a string
from the XML
in order to use it in Response.Write(result)
, here are some ways:
Suppose a small DataSet
created like this:
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)
You can use GetXml
methods from the DataSet
.
Dim simpleresult As String = ds.GetXml
Output:
<NewDataSet>
<Table1>
<Column1>Value1</Column1>
<Column2>Value2</Column2>
</Table1>
<Table1>
<Column1>Value3</Column1>
<Column2>Value4</Column2>
</Table1>
</NewDataSet>
You can use WriteXml
methods from the DataSet
or a DataTable
if you want to control XmlWriteMode
. You get the String
using a 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
Output:
<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>
Upvotes: 4