2012-04-03 48 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; 

小哈克,它的作品。我確信有這樣一種更簡潔的方式,但我想我會分享我的成功,因爲我沒有找到任何好的例子。