如何使用 XSD 检查 XML 是否缺少元素
XSD 文件中
的 minOccurs
属性的默认值为 1 (来源)。
假设您有一个 XSD,指定包含 2 个元素的复杂类型:
和
。
如果您提供仅包含
的 XDocument
,则 XDocument
将不会验证。
相反,您会收到消息:
The element Message in namespace ___ has invalid child element el2 in namespace ___. List of possible elements expected: el1
这基本上是
上的错误,人们会期望复杂类型上出现不包含
我的问题是:
有没有办法检查所有具有 minOccurs
> 的
标签? 0 人在场?
我想说,这是使用 XSD 验证 XML 时非常基本的检查。
The default for minOccurs
property of an <element>
in an XSD file is 1 (source).
Consider you have an XSD specifying a complex type containing 2 elements: <el1>
and <el2>
.
If you provide an XDocument
only containing <el2>
, the XDocument
will not validate.
Instead you'll get the message:
The element Message in namespace ___ has invalid child element el2 in namespace ___. List of possible elements expected: el1
This basically is an error on <el2>
where one would expect an error on the complex type for not containing <el1>
.
My question is:
Is there a way to check if all <element>
-tags which have minOccurs
> 0 are present?
I would say this is a very basic check when validating XML with an XSD.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您定义架构的方式,元素的出现顺序很重要。
在这种情况下,验证器期望得到一个。但看到元素所以错误是出现在不该出现的地方。我相信这意味着您在定义复杂类型时使用了“序列”。所以你得到的错误是正确的。
如果这仍然困扰您,并且元素的顺序对您的解析并不重要,请使用“全部”而不是“序列”,这不会强制执行顺序。然后,验证器应提示您输入必需的元素。失踪了。它应该类似于以下内容:
我希望这会有所帮助。
Depending on the way you defined your schema, the order of appearance of elements will matter.
In this case the validator is expecting a <el1> but is seeing the element <el2> so the error is that <el2> is appearing where it should not. I belive that means you used a "sequence" when defining your complex type. So the error you at getting is correct.
If this still bothers you, and the order of the elements does not matter to your parsing use "all" instead of "sequence" which will not enforce order. The validator should then prompt you that a required element <el1> is missing. It should look something like the following:
I hope this helps.