使用Xerces在Android上根据模式验证XML

使用Xerces在Android上根据模式验证XML,android,xml,validation,schema,xerces,Android,Xml,Validation,Schema,Xerces,因此,在咨询javax.xml.validation库在Android上不起作用之后,我不得不找到另一个解决方案。我已经尝试过使用Xerces API,尽管它似乎对很多人都很好,但我无法让它正常工作 我使用的是存储在SD卡文件中的本地XML模式 我使用的代码如下: public static boolean validate(String XmlDocumentUrl, String SchemaUrl) { SAXParser parser = new SAXParser();

因此,在咨询javax.xml.validation库在Android上不起作用之后,我不得不找到另一个解决方案。我已经尝试过使用Xerces API,尽管它似乎对很多人都很好,但我无法让它正常工作

我使用的是存储在SD卡文件中的本地XML模式

我使用的代码如下:

    public static boolean validate(String XmlDocumentUrl, String SchemaUrl) {
    SAXParser parser = new SAXParser();
    try {

        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setFeature("http://apache.org/xml/features/validation/schema", true);
        parser.setFeature("http://apache.org/xml/features/standard-uri-conformant", false);
        parser.setProperty(
                "http://apache.org/xml/properties/schema/external-schemaLocation",
                "http://www.topografix.com/GPX/1/0 file:///mnt/sdcard/gpxSchema1.0.xsd");



        Validator handler = new Validator();

        parser.setErrorHandler(handler);
        parser.parse(XmlDocumentUrl);
        if (handler.validationError == true){
            System.out.println("XML Document has Error:"

                    + handler.validationError + ""
                    + handler.saxParseException.getMessage());
        return false;
        }
        else{
            System.out.println("XML Document is valid");
        return true;
        }
    } catch (java.io.IOException ioe) {
        System.out.println("IOException" + ioe.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException" + e.getMessage());
    }
    return false;
}

private static class Validator extends DefaultHandler {
    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    public void error(SAXParseException exception) throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void fatalError(SAXParseException exception) throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void warning(SAXParseException exception) throws SAXException {
    }
}
04-03 18:12:05.125: E/AndroidRuntime(20457): FATAL EXCEPTION: main
04-03 18:12:05.125: E/AndroidRuntime(20457): java.lang.***ExceptionInInitializerError***
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.configurePipeline(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XIncludeAwareParserConfiguration.configurePipeline(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.util.XMLSchemaValidator2.validate(XMLSchemaValidator2.java:29)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.schemas.StrategyGPXSchema1_0.validate(StrategyGPXSchema1_0.java:11)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.schemas.GPXSchemaValidatorGeneral.executeStrategy(GPXSchemaValidatorGeneral.java:13)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.GPXValidator.isValidAgainstSchema(GPXValidator.java:115)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.GPXValidator.validate(GPXValidator.java:34)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.ValidatorGeneral.executeStrategy(ValidatorGeneral.java:15)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.MecheTrackParser.isValidMecheFile(MecheTrackParser.java:55)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.MecheTrackParser.parse(MecheTrackParser.java:30)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.statePattern.states.InitState.selectFile(InitState.java:33)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.main.MecheModel.selectFile(MecheModel.java:39)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.MecheActivity$1.onClick(MecheActivity.java:118)
通过试验此代码,我认为这是问题的根源:
parser.setProperty(
"http://apache.org/xml/properties/schema/external-schemaLocation",
"http://www.topografix.com/GPX/1/0 file:///mnt/sdcard/gpxSchema1.0.xsd");

我认为由于某种原因,找不到.xsd文件,但我不确定。 如果有人能向我们解释我做错了什么,或者是否有与该房产无关但仍然不对的事情,我会很高兴

我得到的错误如下:

    public static boolean validate(String XmlDocumentUrl, String SchemaUrl) {
    SAXParser parser = new SAXParser();
    try {

        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setFeature("http://apache.org/xml/features/validation/schema", true);
        parser.setFeature("http://apache.org/xml/features/standard-uri-conformant", false);
        parser.setProperty(
                "http://apache.org/xml/properties/schema/external-schemaLocation",
                "http://www.topografix.com/GPX/1/0 file:///mnt/sdcard/gpxSchema1.0.xsd");



        Validator handler = new Validator();

        parser.setErrorHandler(handler);
        parser.parse(XmlDocumentUrl);
        if (handler.validationError == true){
            System.out.println("XML Document has Error:"

                    + handler.validationError + ""
                    + handler.saxParseException.getMessage());
        return false;
        }
        else{
            System.out.println("XML Document is valid");
        return true;
        }
    } catch (java.io.IOException ioe) {
        System.out.println("IOException" + ioe.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException" + e.getMessage());
    }
    return false;
}

private static class Validator extends DefaultHandler {
    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    public void error(SAXParseException exception) throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void fatalError(SAXParseException exception) throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void warning(SAXParseException exception) throws SAXException {
    }
}
04-03 18:12:05.125: E/AndroidRuntime(20457): FATAL EXCEPTION: main
04-03 18:12:05.125: E/AndroidRuntime(20457): java.lang.***ExceptionInInitializerError***
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.configurePipeline(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XIncludeAwareParserConfiguration.configurePipeline(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.util.XMLSchemaValidator2.validate(XMLSchemaValidator2.java:29)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.schemas.StrategyGPXSchema1_0.validate(StrategyGPXSchema1_0.java:11)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.schemas.GPXSchemaValidatorGeneral.executeStrategy(GPXSchemaValidatorGeneral.java:13)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.GPXValidator.isValidAgainstSchema(GPXValidator.java:115)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.gpx.GPXValidator.validate(GPXValidator.java:34)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.validation.ValidatorGeneral.executeStrategy(ValidatorGeneral.java:15)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.MecheTrackParser.isValidMecheFile(MecheTrackParser.java:55)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.inputhandling.MecheTrackParser.parse(MecheTrackParser.java:30)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.statePattern.states.InitState.selectFile(InitState.java:33)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.main.MecheModel.selectFile(MecheModel.java:39)
04-03 18:12:05.125: E/AndroidRuntime(20457):    at com.pe60t0.Meche.MecheActivity$1.onClick(MecheActivity.java:118)

问题是android没有xerces和验证接口=) 顺便说一句,box中的xerces不适用于android,因为有些类被排除在最终APK之外,因为它们使用不同的目标编译。 但您可以简单地从xerce添加验证:

您可以在adnroid中使用xerces和本机模式验证(java)-您必须下载xerces源代码并(经过一些简单的操作)将其包含到您自己的代码中-您将能够使用DocumentBuilderFactory.setShema方法


这是一个众所周知的问题,由谷歌发布在

解决方案是使用ApacheXerces像你说的那样移植到Android。这里有一个项目

您必须执行svn chekout并将项目导出到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");

我发现我无法让常规的xerces与Android一起工作,但我确实找到了适用于Android的xerces,我已经开始工作了。下面是设置的详细信息和一些示例代码。祝你好运:)

以下几点对我很有用:

  • 创建一个验证实用程序
  • 在android操作系统上将xml和xsd都放入文件中,并对其使用验证实用程序
  • 使用Xerces For Android进行验证
  • Android确实支持一些我们可以使用的软件包,我基于以下内容创建了我的xml验证实用程序:

    我最初使用java进行的沙盒测试非常顺利,然后我尝试将其移植到Dalvik,发现我的代码无法工作。Dalvik不支持同样的东西,所以我做了一些修改

    我找到了一个对xerces for android的引用,因此我修改了我的沙盒测试(以下内容不适用于android,后面的示例适用于):

    上面的代码必须经过一些修改才能与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),我能够获得以下用于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;   
    
    有点老套,它很管用。我相信有一种更简洁的方法可以做到这一点,但我想我会分享我的成功,因为我没有找到任何好的例子