2012-04-03 5 views
1

this threadで、javax.xml.validationライブラリがAndroidで動作しないことを確認した後、別の解決策を見つけなければなりませんでした。私はXerces APIを使用しようとしましたが、多くの人にとってうまくいきますが、正しく動作するようにはできません。Xercesを使用してAndroidのスキーマに対してXMLを検証する

私は、sdcardのファイルに格納されているローカル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ファイルは見つかりませんでしたが、わかりません。 誰かが私が間違っていることを説明することができれば、またはこの物と無関係な何かがあり、それでもまだ正しくない場合は、私は幸せになるでしょう。

私が手にエラーが次のとおりです。いくつかのために、アンドロイドでは動作しません)=問題はアンドロイドがXercesのを持っているとのインタフェースを検証していないということです

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

そしてところでボックスからASISをXERCESクラスは異なるターゲットでコンパイルされているため、最終APKから除外されます。 しかし、xerceからのバリデーションを追加するだけでいいです:

aderroidでxercesとネイティブのスキーマの検証(javaで)を使うことができます - xercesのソースをダウンロードして(単純な操作の後で)自分のコードにインクルードする必要がありますDocumentBuilderFactory.setShemaメソッドを使用することができます。

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

0

それは解決策は、Apache Xercesのは、あなたが言うようにAndroidに移植され使用されhttp://code.google.com/p/android/issues/detail?id=7395

でGoogleが掲載knowed問題です。ここにプロイェクトがありますhttp://code.google.com/p/xerces-for-android/

svn chekoutを実行して、proyectをjarファイルにエクスポートして、アンドロイドの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のは、Androidで動作するように取得することができませんでした。以下は、セットアップの詳細といくつかのコード例です。幸運:)

以下は、私の仕事:

  1. 検証ユーティリティを作成します。
  2. xmlとxsdの両方をアンドロイド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ではサポートされていないものもありますので、いくつか修正しました。

Iは、AndroidのためのXercesへの参照を見つけたので、私は(これはをした後以下は、アンドロイドとの例を動作しない)の私のサンドボックステストを修飾:

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; 
    } 
} 

上記のコードがありましたアンドロイド(http://gc.codehum.com/p/xerces-for-android/)用のxercesで動作するように修正されました。あなたは、いくつかのベビーベッドノートです以下、プロジェクトを取得するにはSVNが必要になります。上記のjar(結局私はちょうど速いテストのための私のソースに直接、それをコピーし、瓶にそれを作ってあげると

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 

あなたの場合、私は次のように私のxmlの検証のために働くことを得ることができた)あなたはアリ(http://ant.apache.org/manual/using.html)を素早く瓶を作ることができ、同じことをしたい:

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を作成するためにレ、私は、ファイルに文字列を書くための簡単なファイルユーティリティを作った:

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; 

少しハキッシュ、それは動作します。私はこれを行うためのより簡潔な方法があると確信していますが、私が見つけた良い例はないので、私は私の成功を分かち合うと思いました。

関連する問題