XMLSchema validation on Android

纵然是瞬间 提交于 2019-12-03 23:01:37

I'm fascinated that, after several years, this still is an open issue. There only seems to be bad news, though. According to the AOSP Issue Tracker Schema validation currently seems unsupported with the standard Android APIs and Google seems to be unwilling to fix it:

Our XML APIs (including SAX, XmlPull and DOM) don't support any of the following:

 XML Schema 

 XML DTDs (including external entity declarations and references)
 validation

 element content whitespace

However, one commenter of that same ticket references a workaround, and provides example code using a Xerces port. I don't know if this goes beyond what you've figured out, so far, but I hope it helps.

To wrap this up: The SchemaFactoryFinder only knows the following Schema definitions:

Using any other schema definition causes it to fail (It will however log this on debug level). Obviously this is the case for you, as you're using another reference to the 2011 schema. So "correctly" referencing the Schema Definition should fix this issue.

I am using

javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.parsers.ParserConfigurationException;

If you got a XML string you can parse it by:

Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);

please don't forget the exception handling.

I think you could use RelaxNG - there are plenty of validators available. http://relaxng.org/#validators

Of particular interest should be - http://www.kohsuke.org/relaxng/bali/doc/ - https://msv.java.net/ - http://www.davidashen.net/rnv.html

The latter is C implementation, the first two are written in Java.

If you need high performance, you could write some JNI code and call functions in the rnv source. A simpler approach would be to just build rnv for Android, using NDK and then call it's executable with parameters.

Something like

Process p = Runtime.exec("/path/to/rnv/exec", [valdidationDoc: String, some more params]);
OutputStream out = p.getOutputStream(); // connected to STDIN of p
InputStream in = p.getInputStream(); // connected to STDOUT of p
out.write(new FileInputStream("/path/to/xml"));

/// read in for succes/errors
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!