2012-04-03 70 views
1

因此,在咨询this thread后,javax.xml.validation库在Android上无法运行,因此我必须找到另一个解决方案。我曾尝试使用Xerces API,虽然它看起来对许多人来说工作正常,但我无法正常工作。使用Xerces根据Android上的模式验证XML

我使用存储在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 { 
    } 
} 

通过这个代码,我在想,这是造成问题进行试验: parser.setProperty( "http://apache.org/xml/properties/schema/external-schemaLocation", "http://www.topografix.com/GPX/1/0 file:///mnt/sdcard/gpxSchema1.0.xsd");

我想,出于某种原因。找不到xsd文件,但我不确定。 如果有人能解释我们做错了什么,或者如果有什么与这个房产无关,并且仍然不正确,我会很高兴。

我得到的错误如下:

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) 

回答

0

的问题是,Android不具备Xerces和验证接口=) 而BTW XERCES ASIS从对话框不android的工作,因为有些类从最终APK中排除,因为它们使用不同的目标进行编译。 但你可以简单地添加从xerce验证:

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

https://stackoverflow.com/questions/13142567/xml-schema-validation-xmlsignature-with-xerces-in-android

0

这是发布由谷歌一段已知的问题在http://code.google.com/p/android/issues/detail?id=7395

的解决方案是使用Apache Xerces的移植到Android像你说的。这里有一个proyect http://code.google.com/p/xerces-for-android/

你必须做一个svn chekout和导出到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"); 
0

我发现我不能够得到正规的Xerces与Android的工作,但是我没有找到的Xerces换机器人,这是我得到的工作。以下是设置和一些示例代码的详细信息。祝你好运:)

以下为我工作:

  1. 创建一个验证工具。
  2. 在android操作系统上同时获取xml和xsd文件,并使用验证实用程序来对付它。
  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的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 

通过上述罐子(最后我会让它变成一个罐子,只是复制它直接进入我的源快速测试如果您希望做同样的,你可以用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; 
    } 
} 

一些旁注:

用于创建fi LES,我做了一个简单的文件工具写字符串的文件:

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; 

小哈克,它的作品。我确信有这样一种更简洁的方式,但我想我会分享我的成功,因为我没有找到任何好的例子。