Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following code performs validation as per your need, <strong>and also tells you the line number where the error occurred during parsing</strong> You will need following jars to run this code</p> <p>Only code change needed is at validateSchema() method where request response args need to be replaced with a string representation of your xml and String representation of your XSD.</p> <p>resolver.jar, xml-apis.jar, serializer.jar, xercesImpl.jar</p> <pre><code>import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XNIException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Performs validation on XML based on the XSD. Overrides the * {@link SAXParser}. * * */ public class ValidateSchema extends SAXParser { /** * Container for current line and coloum number being parsed in the XML. */ private XMLLocator locator; /** * Default public constructor. */ public ValidateSchema() { super(); } /** * Used for obtaining the {@link XMLLocator} locator object. */ @Override public void startDocument( XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { this.locator = locator; super.startDocument(locator, encoding, namespaceContext, augs); } /** * Validates the XML against the provided XSD. * * @param req HttpServletRequest object. * @param resp HttpServletResponse object. * @throws IOException */ public void validateSchema(HttpServletRequest req, HttpServletResponse resp) throws IOException { String content = req.getParameter("data"); String selectbox = req.getParameter("selectbox"); content = content.trim(); // Convert the XML string to byte stream. InputStream is = new ByteArrayInputStream(content.getBytes()); try { this.setFeature(Constants.VALIDATION_PROP, true); this.setFeature(Constants.SCHEMA_PROP, true); this.setFeature(Constants.DYNAMIC_PROP, true); this.setFeature(Constants.SCHEMA_CHECKING_PROP, true); if("1".equalsIgnoreCase(selectbox)) { this.setProperty(Constants.SCHEMA_LOC,"oem.xsd" ); } else if("2".equalsIgnoreCase(selectbox)) { this.setProperty(Constants.SCHEMA_LOC,"carrier.xsd" ); } Validator handler = new Validator(); this.setErrorHandler(handler); InputSource isp = new InputSource(); isp.setByteStream(is); isp.setEncoding("UTF-8"); this.parse(isp); if (handler.validationError == true) { StringBuffer errorMessage = new StringBuffer(512); errorMessage .append("&lt;div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'&gt;") .append(Constants.INVALID_XML_DOCUMENT) .append(" LineNo: ") .append(handler.saxParseException.getLineNumber()) .append(" ColumnNo: ") .append(handler.saxParseException.getColumnNumber()) .append("&lt;br/&gt;") .append(handler.validationError) .append(handler.saxParseException.getMessage()) .append("&lt;/div&gt;"); System.out.println( errorMessage ); } else { StringBuffer validMsg = new StringBuffer(512); validMsg.append("&lt;div style='background: #ebeff9;border: 0px solid #6b90da;height:60px;padding: 5px;'&gt;") .append(Constants.VALID_XML_DOCUMENT).append("&lt;/div&gt;"); System.out.println( validMsg ); } } catch (SAXException e) { StringBuffer errorMessage = new StringBuffer(512); errorMessage .append("&lt;div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'&gt;") .append(Constants.INVALID_XML_DOCUMENT) .append(" LineNo: ") .append(this.locator.getLineNumber()) .append(" ColumnNo: ") .append(this.locator.getColumnNumber()) .append(" &lt;br/&gt;") .append(e.getMessage()) .append("&lt;/div&gt;"); System.out.println( errorMessage ); } catch (Exception e) { StringBuffer errorMessage = new StringBuffer(512); errorMessage .append("&lt;div style='background: #ffebe6;border: 1px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'&gt;") .append(Constants.INVALID_XML_DOCUMENT) .append(" &lt;br/&gt;") .append(e.getMessage()) .append("&lt;/div&gt;"); System.out.println( errorMessage ); } } /** * Writes back the response to client. * * @param msg Response message. * @param resp HttpServletResponse object. * @throws IOException */ private void responseWrite( String msg, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.getWriter().write(msg); } /** * Custom handler for Errors while parsing documents. */ private class Validator extends DefaultHandler { public boolean validationError = false; public SAXParseException saxParseException = null; /** * @throws SAXException */ @Override public void error(SAXParseException exception) throws SAXException { validationError = true; saxParseException = exception; } /** * @throws SAXException */ @Override public void fatalError(SAXParseException exception) throws SAXException { validationError = true; saxParseException = exception; } /** * @throws SAXException */ @Override public void warning(SAXParseException exception) throws SAXException { } } } </code></pre> <p><strong>Constants.Java contains the validation properties that you need to specify</strong></p> <pre><code>public final class Constants { public static final String VALIDATION_PROP = "http://xml.org/sax/features/validation"; public static final String SCHEMA_PROP = "http://apache.org/xml/features/validation/schema"; public static final String DYNAMIC_PROP = "http://apache.org/xml/features/validation/dynamic"; public static final String SCHEMA_CHECKING_PROP = "http://apache.org/xml/features/validation/schema-full-checking"; public static final String SCHEMA_LOC = "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; public static final String VALID_XML_DOCUMENT = "The above XML is valid."; public static final String INVALID_XML_DOCUMENT = "The Document has error at:"; </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload