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;
            }
    
  • 相关阅读:
    [荐]推荐一个shell学习的网站
    [转]linux远程登入不需要密码
    [转] eclipce使用vim 开启装逼模式
    Linux 下查找指令
    nmon 工具的使用
    LaTeX 符号大全
    vim 粘贴复制操作
    linux命令模式下如何切换首行和尾行
    fish 与oh-my-fish 的安装
    vim 粘贴复制操作
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3170929.html
Copyright © 2011-2022 走看看