XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD)。
XML Schema描述了XML的。可以用一个指定的XML Schema来验证某个XML文档,以检查该XML文档是否符合其要求。文档设计者可以通过XML Schema指定一个XML文档所允许的结构和,并可据此检查一个XML文档是否是有效的。XML Schema本身是一个XML文档,它XML语法结构。可以用通用的XML解析器解析它。
一个XML Schema会定义:文档中出现的元素、文档中出现的属性、子元素、子元素的数量、子元素的顺序、元素是否为空、元素和属性的数据类型、元素或属性的默认和固定值。
XSD是DTD替代者的原因,一是据将来的条件可扩展,二是比DTD丰富和有用,三是用XML,四是支持数据类型,五是支持命名空间。
XSD文件的后缀名为.xsd。
WW中在ConfigurationLoader中使用了xsd进行配置文件的验证。
参见public static World Load(string filename, Cache cache)方法中的代码段54-76行:
1 WorldWindSettings settings = finfo.GetValue(null) as WorldWindSettings; 2 3 XmlReaderSettings readerSettings = new XmlReaderSettings(); 4 5 if (settings.ValidateXML) 6 { 7 Log.Write(Log.Levels.Debug, "CONF", "validating " + filename + " against WorldXmlDescriptor.xsd and LayerSet.xsd"); 8 readerSettings.ValidationType = ValidationType.Schema; 9 /* load the schema to validate against instead of hoping for an inline schema reference */10 XmlSchemaSet schemas = new XmlSchemaSet();11 schemas.Add(null, settings.ConfigPath + "/WorldXmlDescriptor.xsd");12 schemas.Add(null, settings.ConfigPath + "/Earth/LayerSet.xsd");13 14 15 readerSettings.Schemas = schemas;16 readerSettings.ValidationEventHandler += new ValidationEventHandler(XMLValidationCallback);17 readerSettings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;18 }19 else20 {21 Log.Write(Log.Levels.Debug, "CONF", "loading " + filename + " without validation");22 readerSettings.ValidationType = ValidationType.None;23 }
事件方法:
1 public static void XMLValidationCallback(object sender, ValidationEventArgs args) 2 { 3 string file = "(unknown)"; 4 XmlReader reader = sender as XmlReader; 5 if (reader != null) 6 file = reader.BaseURI; 7 8 if (args.Severity == XmlSeverityType.Warning) 9 {10 Log.Write(Log.Levels.Warning, "CONF", "Warning: " + args.Message);11 Log.Write(Log.Levels.Warning, "CONF", " in " + file);12 }13 else14 {15 Log.Write(Log.Levels.Error, "CONF", "Error: " + args.Message);16 Log.Write(Log.Levels.Error, "CONF", " in " + file);17 //throw args.Exception;18 }19 }
参考文献:
###