3

我有一些DataTables想要导出到xml文件中。我可以DataTable.WriteXml()用来输出 to 的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
4

1 回答 1

3

您需要string从中获取 aXML才能在 中使用它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>
    
  • 如果您想控制,可以使用或 a中的WriteXml方法。你得到了使用.DataSetDataTableXmlWriteModeStringMemoryStream

    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>
    
于 2013-06-18T19:06:59.437 回答