1. 程式人生 > >使用xsd驗證xml檔案是否規範

使用xsd驗證xml檔案是否規範

 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}\n", 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}\n", e.Message);
        }
    }