简体   繁体   English

如何使用复杂的验证规则来验证XML文档?

[英]How to validate XML document with complex validation rules?

I have to validate a XML which has many complex validation rules. 我必须验证具有许多复杂验证规则的XML。 I was thinking to define a XSD file to do the validation automatically, but there are some complex ones can't be defined in XSD. 我当时想定义一个XSD文件来自动执行验证,但是在XSD中不能定义一些复杂的文件。

Now I have to write a lot of java code to get values by xpath, validate them one by one, which is very boring to code and test. 现在,我必须编写大量的Java代码才能通过xpath获取值,一个接一个地验证它们,这对代码和测试非常无聊。

I'm looking for an easy way to do this, is there any validation libraries for XML? 我正在寻找一种简便的方法,是否有XML验证库? Or can we define some really complex validation rules in java and used with XSD? 还是可以在Java中定义一些非常复杂的验证规则并与XSD一起使用?


UPDATE: 更新:

I forgot to mention that, I need to add some error code in the error message that to help another team to handle the errors. 我忘了提一下,我需要在错误消息中添加一些错误代码,以帮助另一个团队处理错误。 I'm not sure if XSD can let me do this. 我不确定XSD是否可以让我这样做。


UPDATE AGAIN: 再次更新:

A complex rule: (following paths are under a node of document, say /my-node , not the root) 一条复杂的规则:(以下路径位于文档的节点下,例如/my-node ,而不是根目录)

if /aaa exists
    /bbb should exist
    /ccc should not exist, and
    if /aaa's value is 111:
       /bbb's value should be 222
    if /aaa's value is 555:
       /bbb's value should be 666
else
    /bbb should not exist
    /ccc should exist, and its value should not be number

Java is Turing-complete; Java是图灵完备的; XSD is not. XSD不是。 It follows that there are constraints we can express in Java that cannot be expressed in XSD. 因此,存在一些我们可以用Java表达的约束,而这些约束不能用XSD表达。 (It also suggests that [other things being equal] constraints expressed in XSD are somewhat less likely to contain bugs than equivalent constraints expressed in Java.) (这也表明,与Java中表示的等效约束相比,XSD中表示的[其他条件相同]约束包含错误的可能性要小一些。)

Whether any given set of constraints can be expressed in XSD depends on the constraints. 是否可以在XSD中表达任何给定的约束集取决于这些约束。 From your example, it's hard to tell: your main structure seems to say that if the root element of the document is named aaa , then there should also be a root element named bbb , but not a root element named ccc . 从您的示例中很难看出:您的主要结构似乎说,如果文档的根元素名为aaa ,那么还应该有一个名为bbb的根元素,而不是一个名为ccc的根元素。 This is nonsensical. 这是荒谬的。

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

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