XSD 為定義 XML 檔案格式的 Schema 文件,用來記載 XML 檔案的結構描述。網路傳輸 XML 資料很常見,因此驗證格式是否正確也是一塊很重要的原件。
C# 微軟官方有提供相關的範例給開發者閱讀,小弟也閱讀幾篇不錯部落格分享的實作,修改而成,分享給大家參考。
class SchemaValidation { private static bool isValid = true; /// /// 提供 驗證 XML 是否符合 XSD 格式 /// ///XML File Path ///XSD File Path /// public static bool ValidationSchemaNow(string xmlstring, string schemastring) { XmlDocument doc = new XmlDocument(); doc.Load(xmlstring); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add("urn:bookstore-schema", schemastring); settings.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); XmlNodeReader nodeReader = new XmlNodeReader(doc); XmlReader xr = XmlReader.Create(nodeReader, settings); try { while (xr.Read()) ; } catch (Exception e) { isValid = false; WriteErrorLogs("Validation Warning: " + e.Message); } finally { xr.Close(); } return isValid; } /// /// 驗證處理 Handler /// private static void MyValidationEventHandler(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { WriteErrorLogs("Validation Warning: " + args.Message); } else { WriteErrorLogs("Validation Error: " + args.Message); } isValid = false; } /// /// 錯誤 log 紀錄 /// private static void WriteErrorLogs(string p) { StreamWriter sw = null; try { sw = new StreamWriter(@"D:\xml\erro.txt", true, Encoding.UTF8); sw.WriteLine("[" + DateTime.Now.ToString() + "]" + p); sw.Flush(); sw.Close(); } catch { sw.Close(); } } }
這個 Class 可以驗證傳入的 XML 格式是否符合 XSD 的定義。但如果 XSD 改變程式中 的 settings.Schemas.Add("urn:bookstore-schema", schemastring); 第一個 String 參數也要跟著抽換的 XSD 檔案而改變。而我就沒有將此另外做改寫。
而呼叫的程式碼如下:
static void Main(string[] args) { string xmlfilePath = @"D:\xml\bookSchema.xml"; string xsdfilePath = @"D:\xml\books.xsd"; //利用 XSD 驗證 if (SchemaValidation.ValidationSchemaNow(xmlfilePath, xsdfilePath)) { // do something Console.WriteLine("驗證成功"); } else { Console.WriteLine("驗證失敗"); } Console.Read(); }
沒有留言:
張貼留言