在這一篇文章裡,很完整提到 Parsing XSD 架構的方法:
Parsing XSD Schema with SOM
另相關文:
using XmlArrayItem attribute without XmlArray on Serializable C# class
而我就將它的內容資訊截錄整理到我的Blog。
========================================================
1. 先Parsing 出它的 XmlSchema 物件
private XmlSchema ReadAndCompileSchema(string fileName) {......} private void ValidationCallbackOne(object sender, ValidationEventArgs args) {......}
2. 在取得它的XmlSchema物件後,開始去Loop 它的結構:
(parentTradeName 是專案使用額外加入參數)
tradeNamespace = custSchema.TargetNamespace; foreach (XmlSchemaElement elem in custSchema.Elements.Values) { ProcessElement(elem, ""); } //針對元素處理 private static void ProcessElement(XmlSchemaElement elem) { Console.WriteLine("Element: {0}", elem.Name); if (elem.ElementSchemaType is XmlSchemaComplexType) { XmlSchemaComplexType ct = elem.ElementSchemaType as XmlSchemaComplexType; foreach (DictionaryEntry obj in ct.AttributeUses) Console.WriteLine("Attribute: {0} ", (obj.Value as XmlSchemaAttribute).Name); ProcessSchemaObject(ct.ContentTypeParticle); } else { //一般element的屬性資訊 } } //判斷此Schema Tag 是什麼 private static void ProcessSchemaObject(XmlSchemaObject obj) { if (obj is XmlSchemaElement) ProcessElement(obj as XmlSchemaElement); if (obj is XmlSchemaChoice) ProcessChoice(obj as XmlSchemaChoice); if (obj is XmlSchemaAll) ProcessSchemaAll(obj as XmlSchemaAll, parentTradeName); if (obj is XmlSchemaSequence) ProcessSequence(obj as XmlSchemaSequence); } private void ProcessSequence(XmlSchemaSequence sequence, string parentTradeName) { Console.WriteLine("Sequence"); ProcessItemCollection(sequence.Items, parentTradeName); } private void ProcessChoice(XmlSchemaChoice choice, string parentTradeName) { Console.WriteLine("Choice"); ProcessItemCollection(choice.Items, parentTradeName); } private void ProcessSchemaAll(XmlSchemaAll schemaAll, string parentTradeName) { Console.WriteLine("Choice"); ProcessItemCollection(schemaAll.Items, parentTradeName); } private void ProcessItemCollection(XmlSchemaObjectCollection objs, string parentTradeName) { foreach (XmlSchemaObject obj in objs) ProcessSchemaObject(obj, parentTradeName); }
屬性MEMO:
XmlSchemaElement elem elem.ElementSchemaType //這元素的SchemaType XmlSchemaComplexType ct = elem.ElementSchemaType as XmlSchemaComplexType; ct.ContentTypeParticle //它為 XmlSchemaObject 再判斷它的obj為何種XmlSchema==========================================
因這一次要產生對應的Class程式碼,所以全在 Function ProcessElement() 判斷
if (elem.ElementSchemaType is XmlSchemaComplexType)
{
//它有子層的複雜格式
}
else
{
//Element元素;如:<xs:element name="RspCode" type="xs:string">
}
0 意見 :
張貼留言