2017-08-25 127 views
0

我想从一个DataSet生成的XmlSchema对象中提取数据我有几个表。下面的示例中的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

我不知道你想与读者做什么,作家。 GetXmlSchema()应该为你提供你正在寻找的东西,而不需要其他的代码。 – lancew

+0

对不起,让我改述一下 – user433342

回答

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); 
} 
+0

正是我在找的东西,一定是错过了它,而谷歌搜索。你发现什么微软页面被埋没了? – user433342

+0

我没有,我在调试时发现它。感谢标记作为答案。随时upvote;以及;) – lancew