簡體   English   中英

Android中的XML模式驗證

[英]XML Schema Validation in Android

我已經創建了一個XML,我想使用模式進行驗證,即XSD文件,但是如果我沒有記錯的話,Android不會提供相同的直接類.........並且有一個名為jaxp1.3的外部jar jaxp1.3哪個不允許我編譯代碼,是因為台式機和android的字節碼不同? 里面有類工廠和驗證器,它們做驗證工作……......還有其他選擇嗎? 任何幫助將不勝感激.....拼命尋找ans ..........

這是Google 在這里發布的一個已知問題

解決方案是使用Apache Xerces移植到Android。 有一個項目在這里

您必須執行svn chekout並將proyect導出到jar文件中,以用作android proyect中的庫。

實例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");

@iOSDev,我必須使用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不支持某些功能,因此我進行了一些修改。

我找到了針對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;
    }
}

上面的代碼必須進行一些修改才能與適用於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 )),我可以通過以下操作來進行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;   

有點黑,它的工作原理。 我敢肯定,這樣做有更簡潔的方法,但是我認為我會分享自己的成功,因為我沒有發現任何好的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM