首页 > 代码库 > 使用C#调用Schema文件验证XML文档
使用C#调用Schema文件验证XML文档
C#代码如下:
void Main(){ string errorMessage; ValidateXML(@"C:\Tarena\Backup\数据库\xml\book.xml",@"C:\Tarena\Backup\数据库\xml\book.xsd",out errorMessage).Dump(); errorMessage.Dump();}// Define other methods and classes herestatic bool ValidateXML(string xmlFile,string schemaFile,out string errorMessage){ bool isValid = true; //验证结果 try { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(null,schemaFile); //添加Schema验证文件 XmlReaderSettings readerSetting = new XmlReaderSettings(); readerSetting.ValidationType = ValidationType.Schema; //配置验证方式 readerSetting.Schemas = schemaSet; using (XmlReader xmlReader = XmlReader.Create(xmlFile, readerSetting)) { while (xmlReader.Read()){} } errorMessage = string.Empty; } catch (Exception ex) { isValid = false; errorMessage = ex.Message; } return isValid;}
其中XML文件
<?xml version="1.0" encoding="utf-8"?><books xmlns="http://www.w3.org/2001/XMLSchema"> <book id="1"> <title>西游记</title> <author>吴承恩</author> <price>10.99</price> <pubdate>2010-01-01</pubdate> <category>文学类</category> </book> <book id="2"> <title>三国演义</title> <author>罗贯中</author> <price>20.99</price> <pubdate>2010-02-01</pubdate> <category>文学类</category> </book> <book id="3"> <title>红楼梦</title> <author>曹雪芹</author> <price>30.99</price> <pubdate>2010-03-01</pubdate> <category>文学类</category> </book> <book id="4"> <title>水浒传</title> <author>施耐庵</author> <price>40.99</price> <pubdate>2010-04-01</pubdate> <category>文学类</category> </book></books>
验证文件(Schema)
<?xml version="1.0" encoding="utf-8"?><xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="book.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="books"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="book"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string" /> <xs:element name="author" type="xs:string" /> <xs:element name="price" type="xs:decimal" /> <xs:element name="pubdate" type="xs:date" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element></xs:schema>
使用C#调用Schema文件验证XML文档
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。