xsdを使用してxmlファイルが仕様されているかどうかを検証します.

1897 ワード

 public class XmlValidation
    {
        StringBuilder sb;
        public  string XmlValidationByXsd(string XmlPath,string XsdPath)
        {
            sb= new StringBuilder();
            string strReturnValue = string.Empty;
            
            string dataFile = XmlPath;
            string schemaFile = XsdPath;
	    //  :   xsd          targetNamespace
            string namespaceUrl = "http://www.xxx.cn/xxx";

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(namespaceUrl, schemaFile);
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

            string errorMessage = "              ";
            
            XmlReader reader = XmlReader.Create(dataFile, settings);
            try
            {
                reader.MoveToContent();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Document && reader.NamespaceURI != namespaceUrl)
                    {
                        strReturnValue = errorMessage;
                        break;
                    }
                }
            }
            catch (XmlException ex)
            {
                sb.AppendFormat("{0}
", ex.Message); } finally { reader.Close(); } if (sb.Length == 0) strReturnValue = "true"; else strReturnValue = sb.ToString(); return strReturnValue; } void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e) { sb.AppendFormat("{0}
", e.Message); } }