C# 使用xsd文件验证XML 格式是否正确
核心示例代码:
-
- XmlDocument doc = new XmlDocument();
-
- doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
-
- XmlElement results = doc.CreateElement("KYTResults");
-
-
- XmlNode resultsStatus = doc.CreateElement("ResultsStatus");
-
- XmlElement element = doc.CreateElement("Level");
- element.InnerText = status ? "0" : "1";
- resultsStatus.AppendChild(element);
-
- element = doc.CreateElement("Description");
- element.InnerText = msg;
- resultsStatus.AppendChild(element);
-
- element = doc.CreateElement("PassKey");
- element.InnerText = key;
- resultsStatus.AppendChild(element);
- results.AppendChild(resultsStatus);
-
-
-
- if (status)
- {
- results.AppendChild(dataList);
- }
-
- doc.AppendChild(results);
-
-
- string path = Server.MapPath("/ws/xsd/ReceiveReturn.xsd");
-
- string error = "";
-
- 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;
-
- doc.Validate(eventHandler);
-
- if (!"".Equals(error))
- {
- throw new Exception(error);
- }
|
请发表评论