.Net验证XML文档
为了在XML文档中关联外部的 XSD Schema文件,要对XML文档以及XSD Schema文件作出相应的修改,具体的修改如下示例所示:
XML文件:
<?xml version="1.0" encoding="utf-8" ?> <person xmlns="http://www.xxx.com/xxx"> <name>张飞1111111</name> <age>24</age> </person>
XML Schema文件:
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.xxx.com/xxx"> <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="name"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="4"/> <xs:minLength value="2"/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:positiveInteger"> <xs:maxExclusive value="100"/> <xs:minExclusive value="1"/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
代码文件:XmlDocument验证文件
static void Main(string[] args) { XmlDocument doc = new XmlDocument(); //创建文档 doc.Schemas.Add(null, @"C:\Users\Administrator\Desktop\ConsoleApplication1\ConsoleApplication1\person.xsd"); //添加验证架构文件,null为使用默认的命名空间 doc.Load(@"C:\Users\Administrator\Desktop\ConsoleApplication1\ConsoleApplication1\person.xml"); //加载xml文件 doc.Validate(SettingsValidationEventHandler); //执行验证操作,错误处理方法为参数SettingsValidationEventHandler Console.WriteLine("验证通过"); //如果验证通过才会执行到此 Console.ReadKey(); } static void SettingsValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning) { Console.Write("警告信息: "); Console.WriteLine(e.Message); } else if (e.Severity == XmlSeverityType.Error) { Console.Write("错误信息: "); Console.WriteLine(e.Message); } else { } Console.ReadKey(); }
代码文件:XmlReader版本:
static void Main(string[] args) { XmlReaderSettings Settings = new XmlReaderSettings(); // Settings.Schemas.Add(null, @"C:\Users\Administrator\Desktop\ConsoleApplication1\ConsoleApplication1\person.xsd"); Settings.ValidationType = ValidationType.Schema; Settings.ValidationEventHandler += new ValidationEventHandler(SettingsValidationEventHandler); XmlReader reader = XmlReader.Create(@"C:\Users\Administrator\Desktop\ConsoleApplication1\ConsoleApplication1\person.xml", Settings); while (reader.Read()) { } reader.Close(); Console.WriteLine("验证成功!"); Console.ReadKey(); } static void SettingsValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning) { Console.Write("警告信息: "); Console.WriteLine(e.Message); } else if (e.Severity == XmlSeverityType.Error) { Console.Write("错误信息: "); Console.WriteLine(e.Message); } else { } Console.ReadKey(); }