首页 > 代码库 > 使用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文档