I want to validate xml document using xsd schema file stored on my device. Here is my example code:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// schema file on my device
InputStream isSchema = context.getResources().openRawResource(xsd_file);
// InputStream => Source conversion
Source schemaSource = ????
Schema schema = factory.newSchema(schemaSource);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
Question: How can I convert InputStream into Source required by SchemaFactory::newSchema method ?
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
InputStream. read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255. If no byte is available because the end of the stream has been reached, the returned value is -1.
You don't convert, you wrap it.
Source schemaSource = new StreamSource(isSchema);
See: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/transform/stream/StreamSource.html#StreamSource%28java.io.InputStream%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With