6月
19
2006
分類:
最近更新:
2006-06-19
ASP.Net~~ 產生 XML Schema
基於工作需要,我翻了一下 .Net Framework 中對 XML Schema (XSD) 的支援,想找在程式中維護 XML Schema 的方法。找到了兩種方法,一種是使用 System.Xml.Schema 類別,另一種是透過 DataSet 。以下是分別用這兩種方法產生同一份 XML Schema 的程式。
將 DataSet 結構描述資訊寫為 XML 結構描述 (XSD)
DataSet ds = new DataSet("TEST");
DataTable dt = ds.Tables.Add("T1");
dt.Columns.Add("id", typeof(Int32));
dt.Columns.Add("name", typeof(String));
ds.WriteXmlSchema(Console.Out);
使用 System.Xml.Schema 類別
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
XmlSchema schema = new XmlSchema();
// <xs:element name="TEST">
XmlSchemaElement elementTEST = new XmlSchemaElement();
elementTEST.Name = "TEST";
// <xs:complexType>
XmlSchemaComplexType complexType = new XmlSchemaComplexType();
// <xs:choice minOccurs="0" maxOccurs="unbounded">
XmlSchemaChoice choice = new XmlSchemaChoice();
choice.MinOccurs = 0;
choice.MaxOccursString = "unbounded";
// <xs:element name="T1">
XmlSchemaElement elementT1 = new XmlSchemaElement();
elementT1.Name = "T1";
// <xs:complexType>
XmlSchemaComplexType complexType2 = new XmlSchemaComplexType();
// <xs:sequence>
XmlSchemaSequence sequence = new XmlSchemaSequence();
// <xs:element name="ID" type="xs:int">
XmlSchemaElement elementID = new XmlSchemaElement();
elementID.Name = "ID";
elementID.SchemaTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");
// <xs:element name="Name" type="xs:string">
XmlSchemaElement elementName = new XmlSchemaElement();
elementName.Name = "Name";
elementName.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
sequence.Items.Add(elementID);
sequence.Items.Add(elementName);
complexType2.Particle = sequence;
elementT1.SchemaType = complexType2;
choice.Items.Add(elementT1);
complexType.Particle = choice;
elementTEST.SchemaType = complexType;
schema.Items.Add(elementTEST);
schema.Write(Console.Out);
粗略試了一下,很明顯,直接操作 System.Xml.Schema 是個笨方法,這種方法的程式碼,比它產生的 XML Schema 的文件內容還多。藉由 DataSet 作為中介變數,不僅程式簡化許多,也直接對應 Database table 的 Schema ,我們向 Database 查詢並將結果存入 DataSet 後,可以直接一個 WriteXMLSchema() 就獲得對應 Database table schema 的 XML Schema,在操作上反而更為直覺。
樂多舊網址: http://blog.roodo.com/rocksaying/archives/1776571.html