The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

dwschulze (36) [Avatar] Offline
Groovy makes it simple to parse XML, but how do you validate your XML against an XSD with Groovy?
kenneth.kousen (57) [Avatar] Offline
Re: How to validate XML in Groovy
The XmlParser and XmlSlurper classes from Groovy are really just wrappers for standard SAX parsers. In addition to the default constructor, in each class there is a constructor that takes two boolean arguments. The first is called "validating" and the second is called "namespaceAware".

You would think that means just by setting both to true you would get a validating parser. In a way, that's true. What you actually get is a parser that knows how to validate against a DTD (remember those?), but not against a schema.

(Incidentally, the default constructor sets validating to false and namespaceAware to true.)

That doesn't Groovy can't validate XML against a schema, only that you can't use the XmlParser or XmlSlurper to do it. If you check out you'll see the steps needed to validate against a schema. You'll probably notice that they're the exact same steps you would use with Java, just written in Groovy.

That's actually a good principle. If you can do it in Java and you don't know how to do it in Groovy, just write the Java code. If it turns out there was an easier way, somebody will eventually show you how to make your code groovier.

Again, thanks for reading.