SchemaFactory在8级平台中不支持W3C XML Schema?

32

使用Android SDK时,以下代码在一个空的Activity中会失败:

@Override
protected void onStart() {
    super.onStart();

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}

2.2模拟器logcat显示了这个异常:

06-28 05:38:06.107: WARN/dalvikvm(495): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-28 05:38:06.128: ERROR/AndroidRuntime(495): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.HelloWorldActivity}: java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
        at android.app.ActivityThread.access$2300(ActivityThread.java:125)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4627)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:521)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
        at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:194)
        at com.example.HelloWorldActivity.onStart(HelloWorldActivity.java:26)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
        at android.app.Activity.performStart(Activity.java:3781)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
        ... 11 more

SchemaFactory 的 Javadoc 中提到“平台默认的 SchemaFactory 是以一种实现特定的方式进行定位的。必须有一个面向 W3C XML Schema 的平台默认的 SchemaFactory。”


我在平台级别9和10上遇到了相同的问题。正如this answer所述,目前Android中似乎没有XML Schema支持。 - Joao Azevedo
看起来很相似,但是答案并没有帮助。 - Captain Charmi
2个回答

4
我曾经遇到同样的问题,阅读了很多帖子之后才找到了适合我的答案。在Dalvik上,引用常量是无效的。我发现我必须修改我的代码,以便与Xerces-for-Android项目配合使用,然后我就能够得到我想要的XML验证了。这很可能是您通过变量引用正在做的事情。下面是设置详细信息和一些示例代码,展示如何在Android上实现验证。
以下是适合我的方法:
1. 创建一个验证工具。 2. 将xml和xsd都放入在安卓操作系统中,并使用验证工具进行验证。 3. 使用Xerces-For-Android进行验证。
Android支持我们可以使用的某些包,我基于此创建了我的xml验证工具:http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html 我的初始沙盒测试在Java中非常顺利,但当我尝试将其移植到Dalvik时,发现我的代码无法正常工作。有些事情在Dalvik中的支持方式不同,因此我进行了一些修改。
我找到了关于xerces for android的参考资料,因此我对我的沙盒测试进行了修改(以下示例不适用于Android,请参考下面的示例)。
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;
    }
}

上述代码需要进行一些修改才能在 Android 上使用 xerces (http://gc.codehum.com/p/xerces-for-android/)。获取该项目需要 SVN,以下是一些注意事项:

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

使用上述的jar文件(最终我会将其制作成一个jar文件,现在只是为了进行快速测试而直接复制到我的源代码中。如果您想要做相同的事情,可以使用Ant(http://ant.apache.org/manual/using.html)快速创建jar文件。)我成功地实现了对XML进行验证:

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;
    }
}

一些附注:

为了创建这些文件,我制作了一个简单的文件工具,用于将字符串写入文件:

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();
    }
}

我还需要写入一个我可以访问的区域,因此我使用了:

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

这种方法有点“hackish”,但是可以起到作用。我相信有更简洁的方法,但是因为我没找到好的例子,所以想分享我的成功。


很棒的写作,我欣赏其中详细的程度。 - GMLewisII

1

你可以尝试使用jarjar重新打包xerces,然后传递给其他程序。

"org.apache.xerces.jaxp.validation.XMLSchemaFactory"

至于

SchemaFactory.newInstance(String schemaLanguage, String factoryClassName, ClassLoader classLoader)

如果您正在使用API>=9或直接实例化

org.apache.xerces.jaxp.validation.XMLSchemaFactory 

如果你在使用API 8,那么在比这个API版本更老的版本上使用它可能根本不会起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接