2017-08-25 96 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