Home >Backend Development >C#.Net Tutorial >Detailed explanation of how C# uses xsd files to verify whether the XML format is correct
This article mainly introduces the implementation method of C# using xsd files to verify whether the XML format is correct, and analyzes the C# operation skills related to the creation and verification of xml files in combination with examples. , Friends in need can refer to
The example of this article describes the implementation method of C# using xsd file to verify whether the XML format is correct. Share it with everyone for your reference, the details are as follows:
//创建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); }
The above is the detailed content of Detailed explanation of how C# uses xsd files to verify whether the XML format is correct. For more information, please follow other related articles on the PHP Chinese website!