简体   繁体   中英

How to validate XML document with complex validation rules?

I have to validate a XML which has many complex validation rules. 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.

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.

I'm looking for an easy way to do this, is there any validation libraries for XML? Or can we define some really complex validation rules in java and used with 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.


UPDATE AGAIN:

A complex rule: (following paths are under a node of document, say /my-node , not the root)

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; XSD is not. It follows that there are constraints we can express in Java that cannot be expressed in 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.)

Whether any given set of constraints can be expressed in XSD depends on the constraints. 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 . This is nonsensical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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