安卓中的XML模式验证

3
我已经创建了一个XML文件,想要使用XSD文件进行验证,但是安卓系统没有提供直接的类来实现这个功能,如果我没有理解错误的话......有一个名为jaxp1.3的外部jar包,它不允许我编译代码,这是因为桌面版和安卓版的字节码不同吗?其中包含了用于验证的类schema factory和validator......是否还有其他可选项?非常感谢您的帮助,我在拼命地寻找答案......
2个回答

4
这是谷歌发布的已知问题(这里)
解决方法是使用移植到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");

3
@iOSDev,我不得不在验证时使用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上的支持并不相同,因此我进行了一些修改。
我找到了关于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;
    }
}

以上代码需要进行一些修改才能与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,但是它有效。我相信有更简洁的方法来做这件事,但是我想分享我的成功,因为我没有找到任何好的例子。


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