Exception: SchemaFactory.newInstance ()

I am trying to validate xml against an android schema, but on the first line of the function itself, when creating an instance factory schema, I get an exception.

Exception line:

schemaFactory = SchemaFactory.newInstance (XMLConstants.W3C_XML_SCHEMA_NS_URI);

I also used XMLSchema-instance and XMLSchema but got the same exception from the start.

I've seen many other people have the same problem like this , but I haven't found an answer to this problem yet.

FYI - I use it in the next function:

public static boolean validateWithExtXSDUsingSAX(String xml, String xsd) throws
        ParserConfigurationException, IOException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        SchemaFactory schemaFactory = null;
        try {
            schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        } catch (Exception e) {
            System.out.println("schema factory error" + e.getMessage());
        }

        SAXParser parser = null;

        try {
            factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(xsd) }));
            parser = factory.newSAXParser();
        } catch (SAXException se) {
            System.out.println("SCHEMA : " + se.getMessage()); // problem in
                                                               // the XSD
                                                               // itself
            return false;
        }

        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(

        new ErrorHandler() {

            public void warning(SAXParseException e) throws SAXException {
                System.out.println("WARNING: " + e.getMessage()); // do
                                                                  // nothing
            }

            public void error(SAXParseException e) throws SAXException {
                System.out.println("ERROR : " + e.getMessage());
                throw e;
            }

            public void fatalError(SAXParseException e) throws SAXException {
                System.out.println("FATAL : " + e.getMessage());
                throw e;
            }
        });

        reader.parse(new InputSource(xml));

        return true;
    } catch (ParserConfigurationException pce) {
        throw pce;
    } catch (IOException io) {
        throw io;
    } catch (SAXException se) {
        return false;
    }
}

      

EDIT

There are some issues with the Java XML validator included in the original Android versions. You can try using Xerces instead, you can download it here:

http://code.google.com/p/xerces-for-android/

While there are no downloads in the downloads section, you can do an SVN check to download the source.

+3


source to share


2 answers


I had the same problem and there were many similar questions there, but no good examples on how to do this. The following is what I did with Xerces-for-Android to get my things to work. Good luck :)

The following worked for me:

  • Create a validation utility.
  • Get both xml and xsd to file on Android OS and use validation utility for it.
  • Use Xerces-For-Android to check.

Android supports some packages we can use, I created my xml validation utility based on: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html

My initial test sandbox was pretty smooth with java, then I tried to pipe it to Dalvik and found my code didn't work. Some things are not supported the same way with Dalvik, so I made some changes.

I found a link to xerces for android, so I changed the sandbox test ( , the following one doesn't work with android, example after that ):

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;

/**
 * A Utility to help with xml communication validation.
 */
public class XmlUtil {

    /**
     * Validation method. 
     * Base code/example from: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html
     * 
     * @param xmlFilePath The xml file we are trying to validate.
     * @param xmlSchemaFilePath The schema file we are using for the validation. This method assumes the schema file is valid.
     * @return True if valid, false if not valid or bad parse. 
     */
    public static boolean validate(String xmlFilePath, String xmlSchemaFilePath) {

        // parse an XML document into a DOM tree
        DocumentBuilder parser = null;
        Document document;

        // Try the validation, we assume that if there are any issues with the validation
        // process that the input is invalid.
        try {
            // validate the DOM tree
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = parser.parse(new File(xmlFilePath));

            // create a SchemaFactory capable of understanding WXS schemas
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // load a WXS schema, represented by a Schema instance
            Source schemaFile = new StreamSource(new File(xmlSchemaFilePath));
            Schema schema = factory.newSchema(schemaFile);

            // create a Validator instance, which can be used to validate an instance document
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(document));
        } catch (Exception e) {
            // Catches: SAXException, ParserConfigurationException, and IOException.
            return false;
        }     

        return true;
    }
}

      

The code above had to be modified to work with xerces for android ( http://gc.codehum.com/p/xerces-for-android/ ). To get the project you need SVN, the following notes:

download xerces-for-android
    download silk svn (for windows users) from http://www.sliksvn.com/en/download
        install silk svn (I did complete install)
        Once the install is complete, you should have svn in your system path.
        Test by typing "svn" from the command line.
        I went to my desktop then downloaded the xerces project by:
            svn checkout http://xerces-for-android.googlecode.com/svn/trunk/ xerces-for-android-read-only
        You should then have a new folder on your desktop called xerces-for-android-read-only

      



With the above jar (I will eventually jar it, just copied it straight to my source for quick testing. If you want to do the same, you can jar quickly with Ant ( http://ant.apache.org /manual/using.html )), I was able to get the following for my XML validation:

import java.io.File;
import java.io.IOException;

import mf.javax.xml.transform.Source;
import mf.javax.xml.transform.stream.StreamSource;
import mf.javax.xml.validation.Schema;
import mf.javax.xml.validation.SchemaFactory;
import mf.javax.xml.validation.Validator;
import mf.org.apache.xerces.jaxp.validation.XMLSchemaFactory;

import org.xml.sax.SAXException;

/**
 * A Utility to help with xml communication validation.
 */public class XmlUtil {

    /**
     * Validation method. 
     * 
     * @param xmlFilePath The xml file we are trying to validate.
     * @param xmlSchemaFilePath The schema file we are using for the validation. This method assumes the schema file is valid.
     * @return True if valid, false if not valid or bad parse or exception/error during parse. 
     */
    public static boolean validate(String xmlFilePath, String xmlSchemaFilePath) {

        // Try the validation, we assume that if there are any issues with the validation
        // process that the input is invalid.
        try {
            SchemaFactory  factory = new XMLSchemaFactory();
            Source schemaFile = new StreamSource(new File(xmlSchemaFilePath));
            Source xmlSource = new StreamSource(new File(xmlFilePath));
            Schema schema = factory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlSource);
        } catch (SAXException e) {
            return false;
        } catch (IOException e) {
            return false;
        } catch (Exception e) {
            // Catches everything beyond: SAXException, and IOException.
            e.printStackTrace();
            return false;
        } catch (Error e) {
            // Needed this for debugging when I was having issues with my 1st set of code.
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

      

Some side notes:

To create files, I created a simple utility to write a string to files:

public static void createFileFromString(String fileText, String fileName) {
    try {
        File file = new File(fileName);
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(fileText);
        output.close();
    } catch ( IOException e ) {
       e.printStackTrace();
    }
}

      

I also needed to write to the scope that I had access to, so I used:

String path = this.getActivity().getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.dataDir;   

      

A bit hackish, it works. I'm sure there is a more concise way to do this, however I figured I'd share my success as there weren't any good examples I found.

+1


source


Link to download jar file xerces-for-android.jar from google repository.



If the link above is not available then use this download page: xerces

0


source







All Articles