This article mainly introduces C # using XSD file to verify the correctness of XML format implementation method, combined with instance form analysis of C # for XML file creation, validation related operations skills, the need for friends can refer to the next
The example in this article describes the implementation of C # using XSD files to verify that the XML format is correct. Share to everyone for your reference, as follows:
// Create xmlDocument
XmlDocument doc = new XmlDocument ();
// Create a declaration section such as <? Xml version = "1.0" encoding = "utf-8"?>
doc.AppendChild (doc.CreateXmlDeclaration ("1.0", "utf-8", null));
// Create a root node KYTResults
XmlElement results = doc.CreateElement ("KYTResults");
// Create ResultsStatus
XmlNode resultsStatus = doc.CreateElement ("ResultsStatus");
// Create Level
XmlElement element = doc.CreateElement ("Level");
element.InnerText = status? "0": "1";
resultsStatus.AppendChild (element);
// Create Description
element = doc.CreateElement ("Description");
element.InnerText = msg;
resultsStatus.AppendChild (element);
// Create PassKey if user login fails
element = doc.CreateElement ("PassKey");
element.InnerText = key;
resultsStatus.AppendChild (element);
results.AppendChild (resultsStatus);
// END create ResultsStatus
// Create a DataList data collection
if (status)
{
results.AppendChild (dataList);
}
// END creates a root node KYTResults
doc.AppendChild (results);
string path = Server.MapPath ("/ ws / xsd / ReceiveReturn.xsd");
// Verify that the xml format is correct
string error = "";
// declare XmlSchema
XmlSchemaSet schemas = new XmlSchemaSet ();
schemas.Add ("", XmlReader.Create (path));
// Declare event processing method
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;
// Verify xml
doc.Validate (eventHandler);
// Check for exceptions if thrown if the format is incorrect
if (! "". Equals (error))
{
throw new Exception (error);
}