xmlsechema验证

               //创建xmlDocument 

               XmlDocument doc = new XmlDocument(); 
   
                //创建声明段 如<?xml version="1.0" encoding="utf-8" ?>  
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); 
                //创建一个根节点 KYTResults 
                XmlElement results = doc.CreateElement("KYTResults"); 
   
                //创建 ResultsStatus 
                XmlNode resultsStatus = doc.CreateElement("ResultsStatus"); 
                //创建Level 
                XmlElement element = doc.CreateElement("Level"); 
                element.InnerText = status ? "0" : "1"
                resultsStatus.AppendChild(element); 
                //创建Description 
                element = doc.CreateElement("Description"); 
                element.InnerText = msg; 
                resultsStatus.AppendChild(element); 
                //创建PassKey 如果用户登录失败 将加载空字符 
                element = doc.CreateElement("PassKey"); 
                element.InnerText = key; 
                resultsStatus.AppendChild(element); 
                results.AppendChild(resultsStatus); 
                //END 创建 ResultsStatus  
   
                //创建 DataList  数据集合 
                if (status) 
                
                    results.AppendChild(dataList); 
                
                //END 创建一个根节点 KYTResults 
                doc.AppendChild(results); 
   
   
                string path = Server.MapPath("/ws/xsd/ReceiveReturn.xsd"); 
   
//验证xml格式是否正确 通过xsd验证 
                    string error = ""
                    //声明XmlSchema 
                    XmlSchemaSet schemas = new XmlSchemaSet(); 
                    schemas.Add("", XmlReader.Create(path)); 
                    //声明事件处理方法 
                    ValidationEventHandler eventHandler = new ValidationEventHandler(delegate(object sender, ValidationEventArgs e) { 
                        switch (e.Severity) 
                        
                            case XmlSeverityType.Error: 
                                error += e.Message; 
                                break
                            case XmlSeverityType.Warning: 
                                break
                        
                    }); 
                    doc.Schemas = schemas; 
                    //验证xml 
                    doc.Validate(eventHandler); 
                    //检查是否有异常 如果格式不正确就抛出来 
                    if (!"".Equals(error)) 
                    
                        throw new Exception(error); 
                    
posted @ 2014-09-04 15:43  小毛驴  阅读(165)  评论(0编辑  收藏  举报