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;}
相关文章推荐
- C# 利用Xsd验证xml
- C# 利用Xsd验证xml
- C# 利用自带xsd.exe工具操作XML-如通过XML生成xsd文件
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
- C# xsd 验证 XML数据有效性 问题
- C# 使用xsd文件验证XML 格式是否正确
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
- 如何用 Visual C#.net 中的 DTD、 XDR,或 XSD 验证 XML 文档
- Xsd 验证xml--C#
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
- C# 利用自带xsd.exe工具操作XML-如通过XML生成xsd文件
- C# 利用自带xsd.exe工具操作XML-如通过XML生成xsd文件
- C#使用xsd文件验证XML 格式是否正确
- Dataset利用xsd读取xml,数值类型处理及验证
- C# 使用xsd文件验证XML 格式是否正确
- C# 利用自带xsd.exe工具操作XML-如通过XML生成xsd文件
- Delphi 7验证XML合法性(利用DTD、XSD)
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
- C#使用XSD来验证XML。