DataSet.GetXml DataSet.GetXml DataSet.GetXml DataSet.GetXml Method

定义

返回存储在 DataSet 中的数据的 XML 表示形式。Returns the XML representation of the data stored in the DataSet.

public:
 System::String ^ GetXml();
public string GetXml ();
member this.GetXml : unit -> string
Public Function GetXml () As String

返回

表示存储在 DataSet 中的数据的字符串。A string that is a representation of the data stored in the DataSet.

示例

下面的示例创建一个DataSetDataTable添加示例数据,然后以 XML 格式显示数据。The following example creates a DataSet and DataTable, adds sample data, and then displays the data in XML format.

private static void DemonstrateGetXml()
{
    // Create a DataSet with one table containing 
    // two columns and 10 rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = dataSet.Tables.Add("Items");
    table.Columns.Add("id", typeof(int));
    table.Columns.Add("Item", typeof(string));

    // Add ten rows.
    DataRow row;
    for(int i = 0; i <10;i++)
    {
        row = table.NewRow();
        row["id"]= i;
        row["Item"]= "Item" + i;
        table.Rows.Add(row);
    }

    // Display the DataSet contents as XML.
    Console.WriteLine( dataSet.GetXml() );
}
Private Shared Sub DemonstrateGetXml()
    ' Create a DataSet with one table 
    ' containing two columns and 10 rows.
    Dim dataSet As New DataSet("dataSet")
    Dim table As DataTable = dataSet.Tables.Add("Items")
    table.Columns.Add("id", Type.GetType("System.Int32"))
    table.Columns.Add("Item", Type.GetType("System.String"))

    ' Add ten rows.
    Dim row As DataRow
    Dim i As Integer
    For i = 0 To 9
        row = table.NewRow()
        row("id") = i
        row("Item")= "Item" & i
        table.Rows.Add(row)
    Next

    ' Display the DataSet contents as XML.
    Console.WriteLine( dataSet.GetXml() )
End Sub

此示例演示如何从数据集将数据写入 XML 文件中并从 XML 中将数据读取到数据集中。This sample demonstrates how to write data into an XML file from a DataSet and read data into DataSet from XML. 此示例将创建一个具有两个表的数据集,使用两种方法将数据集导出到 XML 文件(WriteXml 和 GetXml)中,并使用两种方法(ReadXml 和 InferXmlSchema)从 XML 文件中导入数据集。This sample will create one dataset with two tables, use two ways to export a dataset into the XML files (WriteXml and GetXml), and use two ways (ReadXml and InferXmlSchema) to import a dataset from the XML files.

在编译并运行此示例之前,您需要在示例目录中创建四个 XML 文件。Before you compile and run the sample, you need to create four XML files in the sample directory. 首先,创建 ElementsWithAttributes.xml:First, create ElementsWithAttributes.xml:

<MySchool>  
  <Course CourseID="C1045" Year="2012"  Title="Calculus" Credits="4" DepartmentID="7">New</Course>  
  <Course CourseID="C1061" Year="2012"  Title="Physics" Credits="4" DepartmentID="1" />  
  <Department DepartmentID="1" Name="Engineering" Budget="350000" StartDate="2007-09-01T00:00:00+08:00" Administrator="2" />  
  <Department DepartmentID="7" Name="Mathematics" Budget="250024" StartDate="2007-09-01T00:00:00+08:00" Administrator="3">Cancelled</Department>  
</MySchool>  

接下来,创建 ElementsWithChildElementsxml.xml:Next, create ElementsWithChildElementsxml.xml:

<MySchool>  
  <Course>  
    <CourseID>C1045</CourseID>  
    <Year>2012</Year>  
    <Title>Calculus</Title>  
    <Credits>4</Credits>  
    <DepartmentID>7</DepartmentID>  
  </Course>  
  <Course>  
    <CourseID>C1061</CourseID>  
    <Year>2012</Year>  
    <Title>Physics</Title>  
    <Credits>4</Credits>  
    <DepartmentID>1</DepartmentID>  
  </Course>  
  <Course>  
    <CourseID>C2021</CourseID>  
    <Year>2012</Year>  
    <Title>Composition</Title>  
    <Credits>3</Credits>  
    <DepartmentID>2</DepartmentID>  
  </Course>  
  <Course>  
    <CourseID>C2042</CourseID>  
    <Year>2012</Year>  
    <Title>Literature</Title>  
    <Credits>4</Credits>  
    <DepartmentID>2</DepartmentID>  
  </Course>  
  <Department>  
    <DepartmentID>1</DepartmentID>  
    <Name>Engineering</Name>  
    <Budget>350000</Budget>  
    <StartDate>2007-09-01T00:00:00+08:00</StartDate>  
    <Administrator>2</Administrator>  
  </Department>  
  <Department>  
    <DepartmentID>2</DepartmentID>  
    <Name>English</Name>  
    <Budget>120000</Budget>  
    <StartDate>2007-09-01T00:00:00+08:00</StartDate>  
    <Administrator>6</Administrator>  
  </Department>  
  <Department>  
    <DepartmentID>4</DepartmentID>  
    <Name>Economics</Name>  
    <Budget>200000</Budget>  
    <StartDate>2007-09-01T00:00:00+08:00</StartDate>  
    <Administrator>4</Administrator>  
  </Department>  
  <Department>  
    <DepartmentID>7</DepartmentID>  
    <Name>Mathematics</Name>  
    <Budget>250024</Budget>  
    <StartDate>2007-09-01T00:00:00+08:00</StartDate>  
    <Administrator>3</Administrator>  
  </Department>  
</MySchool>  

现在创建 ElementsWithOnlyAttributes.xml:Now create ElementsWithOnlyAttributes.xml:

<MySchool>  
  <Course CourseID="C1045" Year="2012"  Title="Calculus" Credits="4" DepartmentID="7" />  
  <Course CourseID="C1061" Year="2012"  Title="Physics" Credits="4" DepartmentID="1" />  
  <Department DepartmentID="1" Name="Engineering" Budget="350000" StartDate="2007-09-01T00:00:00+08:00" Administrator="2" />  
  <Department DepartmentID="7" Name="Mathematics" Budget="250024" StartDate="2007-09-01T00:00:00+08:00" Administrator="3" />  
</MySchool>  

最后,创建 RepeatingElements.xml:And finally, create RepeatingElements.xml:

<MySchool>  
  <Course>C1045</Course>  
  <Course>C1061</Course>  
  <Department>Engineering</Department>   
  <Department>Mathematics</Department>  
</MySchool>  

现在您可编译并运行以下源代码。Now you can compile and run the following source code. 对于本示例,如何将数据集的数据存储到 XML 文件中具有 Visual Basic 和C#项目。How to Store Data of DataSet into XML File has Visual Basic and C# projects for this sample.

using System;  
using System.Data;  
using System.IO;  
using System.Text;  
using System.Xml;  
  
// Use WriteXml method to export the dataset.  
static class DataTableHelper {  
   public static void WriteDataSetToXML(DataSet dataset, String xmlFileName) {  
      using (FileStream fsWriterStream = new FileStream(xmlFileName, FileMode.Create)) {  
         using (XmlTextWriter xmlWriter = new XmlTextWriter(fsWriterStream, Encoding.Unicode)) {  
            dataset.WriteXml(xmlWriter, XmlWriteMode.WriteSchema);  
            Console.WriteLine("Write {0} to the File {1}.", dataset.DataSetName, xmlFileName);  
            Console.WriteLine();  
         }  
      }  
   }  
  
   // Use GetXml method to get the XML data of the dataset and then export to the file.  
   public static void GetXMLFromDataSet(DataSet dataset, String xmlFileName) {  
      using (StreamWriter writer = new StreamWriter(xmlFileName)) {  
         writer.WriteLine(dataset.GetXml());  
         Console.WriteLine("Get Xml data from {0} and write to the File {1}.", dataset.DataSetName, xmlFileName);  
         Console.WriteLine();  
      }  
   }  
  
   // Use ReadXml method to import the dataset from the dataset.  
   public static void ReadXmlIntoDataSet(DataSet newDataSet, String xmlFileName) {  
      using (FileStream fsReaderStream = new FileStream(xmlFileName, FileMode.Open)) {  
         using (XmlTextReader xmlReader = new XmlTextReader(fsReaderStream)) {  
            newDataSet.ReadXml(xmlReader, XmlReadMode.ReadSchema);  
         }  
      }  
   }  
  
   // Display the columns and value of DataSet.  
   public static void ShowDataSet(DataSet dataset) {  
      foreach (DataTable table in dataset.Tables) {  
         Console.WriteLine("Table {0}:", table.TableName);  
         ShowDataTable(table);  
      }  
   }  
  
   // Display the columns and value of DataTable.  
   private static void ShowDataTable(DataTable table) {  
      foreach (DataColumn col in table.Columns) {  
         Console.Write("{0,-14}", col.ColumnName);  
      }  
      Console.WriteLine("{0,-14}", "");  
  
      foreach (DataRow row in table.Rows) {  
         if (row.RowState == DataRowState.Deleted) {  
            foreach (DataColumn col in table.Columns) {  
               if (col.DataType.Equals(typeof(DateTime))) {  
                  Console.Write("{0,-14:d}", row[col, DataRowVersion.Original]);  
               }  
               else if (col.DataType.Equals(typeof(Decimal))) {  
                  Console.Write("{0,-14:C}", row[col, DataRowVersion.Original]);  
               }  
               else {  
                  Console.Write("{0,-14}", row[col, DataRowVersion.Original]);  
               }  
            }  
         }  
         else {  
            foreach (DataColumn col in table.Columns) {  
               if (col.DataType.Equals(typeof(DateTime))) {  
                  Console.Write("{0,-14:d}", row[col]);  
               }  
               else if (col.DataType.Equals(typeof(Decimal))) {  
                  Console.Write("{0,-14:C}", row[col]);  
               }  
               else {  
                  Console.Write("{0,-14}", row[col]);  
               }  
            }  
         }  
         Console.WriteLine("{0,-14}", "");  
      }  
   }  
  
   // Display the columns of DataSet.  
   public static void ShowDataSetSchema(DataSet dataSet) {  
      Console.WriteLine("{0} contains the following tables:", dataSet.DataSetName);  
      foreach (DataTable table in dataSet.Tables) {  
         Console.WriteLine("   Table {0} contains the following columns:", table.TableName);  
         ShowDataTableSchema(table);  
      }  
   }  
  
   // Display the columns of DataTable  
   private static void ShowDataTableSchema(DataTable table) {  
      String columnString = "";  
      foreach (DataColumn col in table.Columns) {  
         columnString += col.ColumnName + "   ";  
      }  
      Console.WriteLine(columnString);  
   }  
}  
  
class Program {  
   static void Main(string[] args) {  
      // Create the DataSet  
      DataSet school = new DataSet("MySchool");  
      DataTable course = CreateCourse();  
      DataTable department = CreateDepartment();  
      school.Tables.Add(course);  
      school.Tables.Add(department);  
  
      // Define the constraint between the tables.  
      ForeignKeyConstraint courseDepartFK = new ForeignKeyConstraint("CourseDepartFK", department.Columns["DepartmentID"], course.Columns["DepartmentID"]);  
      courseDepartFK.DeleteRule = Rule.Cascade;  
      courseDepartFK.UpdateRule = Rule.Cascade;  
      courseDepartFK.AcceptRejectRule = AcceptRejectRule.None;  
      course.Constraints.Add(courseDepartFK);  
  
      InsertDepartments(department);  
      InsertCourses(course);  
  
      // Export the dataset to the XML file.  
      Console.WriteLine("Data of the whole DataSet {0}", school.DataSetName);  
      DataTableHelper.ShowDataSet(school);  
  
      String xmlWithSchemaFileName = "WriterXMLWithSchema.xml";  
      String xmlGetDataFileName = "GetXML.xml";  
  
      // Use two ways to export the dataset to the Xml file.  
      DataTableHelper.WriteDataSetToXML(school, xmlWithSchemaFileName);  
      DataTableHelper.GetXMLFromDataSet(school, xmlGetDataFileName);  
  
      // Import the dataset from the XML file.  
      // Use two ways to import the dataset from the Xml file.  
      Console.WriteLine("Read Xml document into a new DataSet:");  
      DataSet newSchool = new DataSet("NewSchool");  
      DataTableHelper.ReadXmlIntoDataSet(newSchool, xmlWithSchemaFileName);  
      DataTableHelper.ShowDataSetSchema(newSchool);  
      Console.WriteLine();  
  
      Console.WriteLine("Infer a schema for a DataSet from an XML document:");  
      InferDataSetSchemaFromXml();  
  
      Console.WriteLine("Press any key to exit.");  
      Console.ReadKey();  
   }  
  
   static DataTable CreateCourse() {  
      DataTable course = new DataTable("Course");  
      DataColumn[] cols ={  
                              new DataColumn("CourseID",typeof(String)),  
                              new DataColumn("Year",typeof(Int32)),  
                              new DataColumn("Title",typeof(String)),  
                              new DataColumn("Credits",typeof(Int32)),  
                              new DataColumn("DepartmentID",typeof(Int32))};  
      course.Columns.AddRange(cols);  
  
      course.PrimaryKey = new DataColumn[] { course.Columns["CourseID"], course.Columns["Year"] };  
  
      return course;  
   }  
  
   static DataTable CreateDepartment() {  
      DataTable department = new DataTable("Department");  
      DataColumn[] cols = {   
                                new DataColumn("DepartmentID", typeof(Int32)),  
                                new DataColumn("Name",typeof(String)),  
                                new DataColumn("Budget",typeof(Decimal)),  
                                new DataColumn("StartDate",typeof(DateTime)),  
                                new DataColumn("Administrator",typeof(Int32))};  
      department.Columns.AddRange(cols);  
  
      department.PrimaryKey = new DataColumn[] { department.Columns["DepartmentID"] };  
  
      return department;  
   }  
  
   static void InsertDepartments(DataTable department) {  
      Object[] rows = {   
                            new Object[]{1,"Engineering",350000.00,new DateTime(2007,9,1),2},  
                            new Object[]{2,"English",120000.00,new DateTime(2007,9,1),6},  
                            new Object[]{4,"Economics",200000.00,new DateTime(2007,9,1),4},  
                            new Object[]{7,"Mathematics",250024.00,new DateTime(2007,9,1),3}};  
  
      foreach (Object[] row in rows) {  
         department.Rows.Add(row);  
      }  
   }  
  
   static void InsertCourses(DataTable course) {  
      Object[] rows ={  
                               new Object[]{"C1045",2012,"Calculus",4,7},  
                               new Object[]{"C1061",2012,"Physics",4,1},  
                               new Object[]{"C2021",2012,"Composition",3,2},  
                               new Object[]{"C2042",2012,"Literature",4,2}};  
  
      foreach (Object[] row in rows) {  
         course.Rows.Add(row);  
      }  
   }  
  
   // Display the results of inferring schema from four types of XML structures  
   private static void InferDataSetSchemaFromXml() {  
      String[] xmlFileNames = {   
  
                                    @"ElementsWithOnlyAttributes.xml",   
                                    @"ElementsWithAttributes.xml",  
                                    @"RepeatingElements.xml",   
                                    @"ElementsWithChildElements.xml" };  
  
      foreach (String xmlFileName in xmlFileNames) {  
         Console.WriteLine("Result of {0}", Path.GetFileNameWithoutExtension(xmlFileName));  
         DataSet newSchool = new DataSet();  
         newSchool.InferXmlSchema(xmlFileName, null);  
         DataTableHelper.ShowDataSetSchema(newSchool);  
         Console.WriteLine();  
      }  
   }  
}  

注解

调用此方法与WriteXml XmlWriteMode将设置为IgnoreSchema时相同。Calling this method is identical to calling WriteXml with XmlWriteMode set to IgnoreSchema.

GetXml将 xml 作为字符串返回,因此需要的开销比WriteXml将 xml 写入文件的开销更多。GetXml returns XML as a string, and therefore requires more overhead than WriteXml to write XML to a file.

如果DataSet使用架构推理构建并使用 XML 或 Web 服务对其进行序列化,则列排序可能会更改。If you build a DataSet using schema inference and serialize it using XML or Web services, the column ordering may change.

适用于

另请参阅