Showing posts with label sytanx. Show all posts
Showing posts with label sytanx. Show all posts

Tuesday, May 5, 2015

Checking XML structure validation

To check the syntax validation for XML files, we can use below piece of code.Implement an error handler to handle the syntax errors.

This does not do any schema validation. 

//DOM model
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);


DocumentBuilder xmlBuilder = factory.newDocumentBuilder();
xmlBuilder.setErrorHandler(new SimpleErrorHandler());
xmlBuilder.parse(new ByteArrayInputStream(myXMLString.getBytes(IOUtil.UTF_8)));


//Handler
public class SimpleErrorHandler implements ErrorHandler
{
public void warning(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
                       //create problem marker
}

public void error(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
                       //create problem marker
}

public void fatalError(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
                       //create problem marker
}
}