C# 利用Xsd验证xml

<?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;
        }

转载于:https://www.cnblogs.com/muzizongheng/p/3170929.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值