这是一个我在http://weblogs.asp.net/stevewellens/archive/2009/01/05/create-an-xsd-schema-without-knowing-a-damn-thing-about-xsd.aspx上看到的文章,写得非常好,
于是仿照着做了一个demo。输出一个xsd文件,和一份xml语句创建的文件。
private void button1_Click(object sender, EventArgs e)
{
DataSet myDS = new DataSet("Schools");
DataTable myDT = new DataTable("Students");myDS.Tables.Add(myDT);
myDT.Columns.Add(new DataColumn("id", typeof(Int32), null, MappingType.Element));
myDT.Columns.Add(new DataColumn("name", typeof(string), null, MappingType.Element));
myDT.Columns.Add(new DataColumn("gender", typeof(string), null, MappingType.Element));
myDT.Columns.Add(new DataColumn("age", typeof(Int32), null, MappingType.Attribute));
myDT.Columns.Add(new DataColumn("classId", typeof(Int32), null, MappingType.Element));
myDT.PrimaryKey = new DataColumn[1] { myDT.Columns["id"]};
DataTable classDT = new DataTable("classes");
myDS.Tables.Add(classDT);
classDT.Columns.Add(new DataColumn("classId", typeof(Int32), null, MappingType.Element));
classDT.Columns.Add(new DataColumn("className", typeof(string), null, MappingType.Element));
classDT.Columns.Add(new DataColumn("classGrade", typeof(Int32), null, MappingType.Element));
classDT.PrimaryKey = new DataColumn[1]{classDT.Columns["classId"]};
ForeignKeyConstraint stuClaFK = new ForeignKeyConstraint("StuClaFK", myDS.Tables["Students"].Columns["classId"], myDS.Tables["classes"].Columns["classId"]);
stuClaFK.DeleteRule = Rule.SetNull;
stuClaFK.UpdateRule = Rule.SetNull;
stuClaFK.AcceptRejectRule = AcceptRejectRule.None;
myDS.Tables["classes"].Constraints.Add(stuClaFK);
myDS.EnforceConstraints = true;
myDS.WriteXmlSchema(@"C:\School.xsd");
DataRow tempRow = myDT.NewRow();
tempRow["id"] = 1;
tempRow["name"] = "steve wellen";
tempRow["gender"] = "man";
tempRow["age"] = 28;
tempRow["classId"] = 1;
myDT.Rows.Add(tempRow);
tempRow = myDT.NewRow();
tempRow["id"] = 2;
tempRow["name"] = "steve phisen";
tempRow["gender"] = "man";
tempRow["age"] = 28;
tempRow["classId"] = 2;
myDT.Rows.Add(tempRow);
tempRow = myDT.NewRow();
tempRow["id"] = 3;
tempRow["name"] = "bob wellen";
tempRow["gender"] = "man";
tempRow["age"] = 28;
tempRow["classId"] = 3;
myDT.Rows.Add(tempRow);
DataRow rowCla = classDT.NewRow();
rowCla["classId"] = 1;
rowCla["className"] = "computer science";
rowCla["classGrade"] = 5;
classDT.Rows.Add(rowCla);
rowCla = classDT.NewRow();
rowCla["classId"] = 2;
rowCla["className"] = "alien science";
rowCla["classGrade"] = 4;
classDT.Rows.Add(rowCla);
rowCla = classDT.NewRow();
rowCla["classId"] = 3;
rowCla["className"] = "society science";
rowCla["classGrade"] = 5;
classDT.Rows.Add(rowCla);
myDS.WriteXml(@"C:\DynamicXML.xml");