zoukankan      html  css  js  c++  java
  • C# 利用Xsd验证xml

    最近做项目时,用到了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;
            }
    
  • 相关阅读:
    阅读笔记
    个人总结
    《软件需求(第二版)》阅读笔记02
    《软件需求(第二版)》阅读笔记01
    问题账户需求分析
    2017年秋季个人阅读计划
    阅读笔记一之《软件需求与分析》
    每日总结1
    开发体会(模块3.商品分类管理)
    个人总结
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3170929.html
Copyright © 2011-2022 走看看