我试图从我有几个表的DataSet生成的XmlSchema对象中提取数据。我下面的示例中的XmlSchema将导出为完整的正确模式,但我不知道如何遍历它。只有一个项目,而元素总是空的。如何访问XmlSchema对象中的表和列元素?
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Xml.Schema;
public class Program
{
public static void Main()
{
DataTable table1 = new DataTable("patients");
table1.Columns.Add("name");
table1.Columns.Add("id", typeof(int));
table1.Rows.Add("sam", 1);
table1.Rows.Add("mark", 2);
DataTable table2 = new DataTable("medications");
table2.Columns.Add("id", typeof(int));
table2.Columns.Add("medication");
table2.Rows.Add(1, "atenolol");
table2.Rows.Add(2, "amoxicillin");
DataSet set = new DataSet("office");
set.Tables.Add(table1);
set.Tables.Add(table2);
using (var reader = new StringReader(set.GetXmlSchema()))
using (var writer = new StringWriter())
{
var schema = XmlSchema.Read(reader, (sender, args) => { });
schema.Write(writer);
writer.Flush();
Console.WriteLine(schema.Elements.Values.Count);
Console.WriteLine(writer.ToString());
}
//Console.WriteLine(set.GetXmlSchema());
}
}
答案 0 :(得分:1)
我不确定为什么它会以这种方式工作,但这证明您的架构对象已正确填充:
string s = set.GetXmlSchema();
using (TextReader w = new StringReader(s)) {
XmlSchema x = XmlSchema.Read(w, null);
XmlSchemaElement e = (XmlSchemaElement)x.Items[0];
XmlSchemaComplexType t = (XmlSchemaComplexType)e.SchemaType;
XmlSchemaChoice c = (XmlSchemaChoice)t.Particle;
XmlSchemaElement e2 = (XmlSchemaElement)c.Items[0];
Console.WriteLine(e2.Name);
}