验证对XSD的XML不考虑XML namesapce [英] Validate xml against xsd without considering xml namesapce

查看:130
本文介绍了验证对XSD的XML不考虑XML namesapce的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码来验证我对XSD XML

I am using following code to validate my xml against xsd.

var isXmlValid = true;
var vinListMessage = "<root xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:test/properties/v1.0\"><test12121 id=\"3\"></test></root>";
var xsdFilePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "schema.xsd");
var schemas = new XmlSchemaSet();
schemas.Add(null, xsdFilePath);
var xmlDocument = XDocument.Parse(vinListMessage);
xmlDocument.Validate(schemas, (o, e) => { isXmlValid = false; });
Console.WriteLine(isXmlValid);

请注意在上面的XML中的xmlns,它的金塔:测试/性能/v1.0
现在在我的XSD我有目标名称的targetNamespace =瓮:testnew /属性/ V1.0这比在XML不同。

Please note the xmlns in the above xml, its urn:test/properties/v1.0. Now in my xsd I have targetnamespace as targetNamespace="urn:testnew/properties/v1.0" which is different than in the xml.

现在无论XML我试图验证对XSD,它总是返回true。但如果我的命名空间匹配,那么其工作罚款。我想避免的命名空间的依赖。有什么建议?

Now whatever xml I try to validate against the xsd it always return true. But If I match the namespaces then its working fine. I want to avoid dependency on namespace. Any suggestions?

推荐答案

该命名空间是元素名称的一部分,所以没有什么可以做,除了确保它们是。正确的

The namespace is a part of the element name, so there's not much you can do other than ensure they are correct.

如果所有的元素命名空间都应该是一样的,你可以验证之前设置的所有元素的名称空间:

If all the element namespaces are supposed to be the same, you could set the namespace on all your elements before validating:

XNamespace ns = "urn:testnew/properties/v1.0";

foreach (var element in xmlDocument.Descendants())
{
    element.Name = ns + element.Name.LocalName;
}

xmlDocument.Validate(...);



不幸的是,如果该命名空间不匹配,那么将XML根据模式是有效的(只要它是公形成)作为模式根本不适的元素。验证的可以的抛出一个警告,说的元素是不能认可的,尽管它无法通过 XDocument.Validate 扩展方法来传递这个标志(据我可以告诉!)。

Unfortunately, if the namespace doesn't match then the XML is valid according to the schema (provided it is well formed) as the schema simply doesn't apply to the elements. The validation can raise a warning to say the elements aren't recognised, though it's not possible to pass this flag via the XDocument.Validate extension method (as far as I can tell!).

这个问题节目使用备用验证方法的XmlReader XmlReaderSettings ,将让你捕捉警告,如果模式不认可的元素。

This question shows an alternate validation method using XmlReader and XmlReaderSettings that would allow you to capture warnings if the schema does not recognise elements.

这篇关于验证对XSD的XML不考虑XML namesapce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆