Project

Profile

Help

RE: Suppress std err output during Schema validation ยป Main.java

Minimal Java class performing schema validation - Trevor Lawrence, 2023-06-01 17:40

 
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.lib.Invalidity;
import net.sf.saxon.lib.InvalidityHandler;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.SchemaValidator;
import net.sf.saxon.trans.XPathException;

public class Main
{

private static final String INVALID_INPUT = "<element><child1/><!-- missing child --><child3/></element>";

private static final String SCHEMA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">\n"
+ "\n"
+ " <xs:element name=\"element\">\n"
+ " <xs:complexType>\n"
+ " <xs:sequence>\n"
+ " <xs:element name=\"child1\"/>\n"
+ " <xs:element name=\"child2\"/>\n"
+ " <xs:element name=\"child3\"/>\n"
+ " </xs:sequence>\n"
+ " <xs:attribute name=\"requiredAttribute\" use=\"required\"/>\n"
+ " </xs:complexType>\n"
+ " </xs:element>\n"
+ "</xs:schema>\n";

public static void main(String[] args) throws SaxonApiException, FileNotFoundException
{
Processor processor = new Processor(true);
processor.getSchemaManager().load(getAsSource(SCHEMA));

SchemaValidator validator = processor.getSchemaManager().newSchemaValidator();
validator.setInvalidityHandler(new CustomInvalidityHandler());

try
{
validator.validate(getAsSource(INVALID_INPUT));
} catch (SaxonApiException e) {
// Ignore
}
}

private static StreamSource getAsSource(String xml)
{
return new StreamSource(new StringReader(xml));
}

private static class CustomInvalidityHandler implements InvalidityHandler
{

@Override
public void startReporting(String s) throws XPathException
{

}

@Override
public void reportInvalidity(Invalidity invalidity) throws XPathException
{
}

@Override
public Sequence endReporting() throws XPathException
{
return null;
}
}
}
    (1-1/1)