您的位置:首页 > 编程语言 > C#

C# 利用Xsd验证xml

2013-07-04 09:29 405 查看
最近做项目时,用到了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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: