安卓模式验证

6

我创建了一个XML文件,同时有一个XSD文件,我需要使用这个模式验证XML文件。请问是否可以提供一个示例来进行验证?还有,在我的项目中应该把XSD文件放在哪里,以便能够使用该模式进行验证。

4个回答

5
根据文档,自API level 8起支持javax.xml.validation
(我将测试并尽快报告)

更新

好的,问题并非如此简单: SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 在8和9 API级别上均出现了IllegalArgumentException的错误,如此处所述。
谷歌搜索无法解决此问题,只能找到相同的失败报告。API已在此处提供,但未提供实现(默认情况下)。

3
这是一个由Google发布的已知问题,可以在这里找到。
解决方案是使用适用于Android的Apache Xerces。可以在这里找到相关项目。
您需要进行svn checkout并将项目导出为jar文件,以便将其作为库在Android项目中使用。
实例化SchemaFactory的代码需要做一些更改。下面是一个示例:
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;

SchemaFactory  factory = new XMLSchemaFactory();
Schema esquema = factory.newSchema(".../file.xsd");

1

这可能帮助不大,但据我所知,Android平台是一个有些受限的Java环境。主要问题是一些API应该是可用的,特别是javax.xml.validation(JDK 1.5及以上版本的一部分!)却不在其中。

因此,您可能需要包含比非截肢Java平台更多的jar文件。 此外,由于黑名单/白名单问题,可能会有添加标准API的限制(这是Google AppEngine的一个大问题,而Android早于它,因此存在类似的挑战)。

除此之外,我建议尝试使用捆绑的XML解析器Xerces来使用javax.xml.validation。有无数的如何操作文档可以参考。


0

经过阅读许多帖子和尝试各种不同的方法,我终于成功地使用Xerces-for-Android使一切正常运转,并为大家精心记录下了这个过程……希望能帮到您 :)

以下是对我有效的处理方式:

  1. 创建一个验证工具。
  2. 将xml和xsd文件都放入android OS中并使用验证工具进行验证。
  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快速制作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,但它能用。我相信有更简洁的方法来做到这一点,但是我想分享我的成功,因为我没有找到任何好的例子。

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