Validating XML against an XSD in Java
I’ve been working on a REST interface for adding, removing, and viewing Hazard information in the database at work (I’m at the Pacific Disaster Center). Setting up REST was pretty easy, but validating the input has been a bit of a problem. Since it took me a while to find a good solution, I figured I’d post how I went about taking care of my validation problems here.
First, I started out with the main resource part, which you can find the basic to anywhere:
(Some code has been hacked down to necessary parts. Leave a comment if you need more complete code.)
I originally had this method accept a Bean that I then used for all my updating or adding. Having it put the data into an InputStream was what took me the longest to figure out, even though it seems so obvious to me now. I probably could have put it into an InputSource or SAXSource if I wanted, but I’m still experimenting. Either way, there are several ways to go about validating.
To start everything off, here is how the input XML looks:
And here is how my XSD looks:
The first way I found is relatively simple. You can read the original article I modified it from called The Java XML Validation API at IBM’s site. Here is my take on it:
Pretty much the same thing their article covers. This will spit me out a nice error when something is not valid that explains why.
The next way that I tried using DOM:
m_logger is just my companies logger class, a customized version of apache log4j.
IBM had another nice article on how to setup an ErrorHandler that I found quite useful. It took me a minute to realize that you have to build your own. (Again, if you would like to see the one I built, just ask in the comments. They are pretty self explanatory though.)
This brings me to the very last one. Using SAX to parse:
That’s about all there is to it. This works perfectly for REST services to make sure that the user inputs good data and leaves you with less error checking in the end. I hope this has been helpful to anyone else out there looking for a way to validate their XML against an XSD using Java.
Recent Comments