<?xml version="1.0" encoding="UTF-8"?> 最近做项目时,用到了xml的序列化与反序列化, 发现最好用xsd来验证xml, 因为反序列化xml不校验xsd。

方法:xmlData变量为xml字符串

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));                     ms.Position = 0;                       string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GetNoNamespaceSchemaLocation(xmlData));
                     XmlReaderSettings settings = new XmlReaderSettings();                     settings.ValidationType = ValidationType.Schema;                     settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;                     settings.IgnoreComments = true;                     settings.IgnoreWhitespace = true;                     settings.Schemas.Add(null, path);                       using (XmlReader xmlReader = XmlReader.Create(ms, settings))                     {                         XmlDocument xmlDocument = new XmlDocument();                         xmlDocument.Load(xmlReader);                         xmlDocument.Validate(ValidationCallBack);                     } 


 
   
         public static string GetNoNamespaceSchemaLocation(string xml)         {             string result = "";               MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));             using (XmlReader xmlReader = XmlReader.Create(memoryStream))             {                 while (xmlReader.Read())                 {                     if (xmlReader.NodeType == XmlNodeType.Element)                     {                         result = xmlReader.GetAttribute("noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");                         break;                     }                 }             }               memoryStream.Close();                          return result;         }           //Display any warnings or errors.         private static void ValidationCallBack(object sender, ValidationEventArgs args)         {             System.Diagnostics.Debug.WriteLine(args.Message);               throw args.Exception;         }