简体   繁体   English

在不考虑xml名称的情况下针对xsd验证xml

[英]Validate xml against xsd without considering xml namesapce

I am using following code to validate my xml against xsd. 我正在使用以下代码针对xsd验证我的xml。

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);

Please note the xmlns in the above xml, its urn:test/properties/v1.0 . 请注意上述xml中的xmlns,其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. 现在在我的xsd中,我有targetnamespace作为targetNamespace="urn:testnew/properties/v1.0" ,它与xml中的不同。

Now whatever xml I try to validate against the xsd it always return true. 现在,无论我尝试针对xsd进行验证的任何xml,它都始终返回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(...);

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. 不幸的是,如果名称空间不匹配,则XML根据模式是有效的(假设它格式正确),因为该模式根本不适用于元素。 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!). 尽管无法通过XDocument.Validate扩展方法传递此标志(据我所知!),但验证可能会发出警告,指出无法识别元素。

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. 此问题显示了使用XmlReaderXmlReaderSettings的替代验证方法,该验证方法将允许您在架构无法识别元素时捕获警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM