4

我正在尝试针对 Android 架构检查 xml,但在函数的第一行,在创建架构工厂实例时,我得到了一个异常。

异常行:

schemaFactory= SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

我也使用过XMLSchema-instanceXMLSchema,但一开始也遇到了同样的异常。

我看到很多其他人也有同样的问题,比如this,但我还没有找到这个问题的答案。

仅供参考 - 我在以下功能中使用它:

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

编辑

Android 原始版本中包含的 Java XML 验证器存在一些问题。您可以尝试使用 Xerces,您可以在此处下载表格:

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

虽然下载部分没有下载,但您可以通过 SVN checkout 下载源代码。

4

2 回答 2

1

我有同样的问题,并在那里发现了很多类似的问题,但没有很好的例子来说明如何做到这一点。以下是我使用 Xerces-for-Android 所做的工作,以使我的东西正常工作。祝你好运 :)

以下对我有用:

  1. 创建验证实用程序。
  2. 将 xml 和 xsd 都放入 android 操作系统上的文件中,并针对它使用验证实用程序。
  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 不支持某些东西,所以我做了一些修改。

我找到了对 android 的 xerces 的引用,所以我修改了我的沙盒测试(以下不适用于 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;
    }
}

上面的代码必须进行一些修改才能与 xerces for android ( 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快速制作jar(http://ant.apache .org/manual/using.html )),我能够获得以下内容来进行我的 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,它有效。我确信有一种更简洁的方法可以做到这一点,但是我想我会分享我的成功,因为我没有找到任何好的例子。

于 2013-09-17T22:27:50.933 回答
0

从 google 存储库下载 jar 文件xerces-for-android.jar的链接。

如果以上链接不可用,请使用此页面下载:xerces

于 2014-12-26T07:38:38.720 回答