I am currently using my XSD to Validate my xml. This part works fine my porblem is that I want to obtain the element of the tag /value that is invalid.
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
XMLStreamReader reader = null;
SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(xsdschemalocation);
Validator validator = schema.newValidator();
try
{
reader = XMLInputFactory.newInstance().createXMLStreamReader(new StreamSource(new StringReader(xml)));
} catch (XMLStreamException ex)
{
LogController.getLogger().logSEVERE("Unable to create the streamreader from the xml source", ex.getLocalizedMessage());
return false;
}
try
{
validator.validate(new StAXSource(reader));
}
catch (IOException ex)
{
LogController.getLogger().logSEVERE("IOException in the validatation has been caused as the reader has become null", ex.getLocalizedMessage());
return false;
}
catch(SAXException saxe)
{
LogController.getLogger().logWARNING("Their is a validation error with the xml", saxe.getLocalizedMessage());
//*****HERE I WANT THE TAG THAT HAS THE ERROR
ClientCommunication.ErrorMessageForClient(VALIDATION_ERROR, socket);
CloseClientConnection();
return;
}
The idea I had which is not practical is to look in the message for the word "type" or "end-tag" and get the value after it, however I know this is not going to be good practice! I find this frustrating as I can see the tag that is invalid but can't get hold of it!
Here are some examples of the element I want
1. Message: Element type "first" must be followed by either attribute specifications, ">" or "/>".
2. javax.xml.stream.XMLStreamException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 353; cvc-pattern-valid: Value '079e989989' is not facet-valid with respect to pattern '([0-9])+' for type 'phoneNumber'.
3. Message: The element type "firstLine" must be terminated by the matching end-tag "</firstLine>".
Below is a way that you could implement your use case using an
ErrorHandler
:MyErrorHandler
I would recommend implementing an
ErrorHandler
that maintained a reference to theXMLStreamReader
so that when aSAXParseException
occurs you could interrogate theXMLStreamReader
to get information about the element. If you want the parsing to stop once an exception is thrown simply rethrow theSAXParseException
at the end of each of the methods.Demo
You set an instance of
ErrorHandler
on theValidator
.schema.xsd
Below is a sample XML schema I used when writing the demo code.
input.xml
Below is some sample input. The
bar
element has invalid content.Output
Below is the output from running the demo code: