public static boolean validateXml(XmlObject xml) {
boolean isXmlValid = false;
// A collection instance to hold validation error messages.
ArrayList validationMessages = new ArrayList();
// Validate the XML, collecting messages.
isXmlValid = xml.validate(
new XmlOptions().setErrorListener(validationMessages));
// If the XML isn't valid, print the messages.
if (!isXmlValid)
{
System.out.println("\nInvalid XML: ");
for (int i = 0; i < validationMessages.size(); i++)
{
XmlError error = (XmlError) validationMessages.get(i);
System.out.println(error.getMessage());
System.out.println(error.getObjectLocation());
}
}
return isXmlValid;
}
Validates the XML, printing error messages when the XML is invalid. Note
that this method will properly validate any instance of a compiled schema
type because all of these types extend XmlObject.
Note that in actual practice, you'll probably want to use an assertion
when validating if you want to ensure that your code doesn't pass along
invalid XML. This sample prints the generated XML whether or not it's
valid so that you can see the result in both cases.
|