2010-03-07 31 views
8
private void validateXML(DOMSource source) throws Exception { 
    URL schemaFile = new URL("http://www.csc.liv.ac.uk/~valli/modules.xsd"); 
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); 
    Schema schema = schemaFactory.newSchema(schemaFile); 

    Validator validator = schema.newValidator(); 
    DOMResult result = new DOMResult(); 
    try { 
     validator.validate(source, result); 
     System.out.println("is valid"); 
    } catch (SAXException e) { 
     System.out.println("not valid because " + e.getLocalizedMessage()); 
    } 
} 

Nhưng điều này trả về một lỗi nói: ngoại lệ trong chủ đề java.lang.IllegalArgumentException "chính": Không SchemaFactory mà thực hiện các ngôn ngữ lược đồ xác định bởi: http://www.w3.org/2001/XMLSchema -instance thể được nạpJava xác nhận XML dựa trên XSD Schema

Đây có phải là sự cố với mã của tôi hoặc với tệp xsd thực tế không?

Trả lời

16

Lỗi đó có nghĩa là Java đã cài đặt của bạn không có bất kỳ lớp nào có thể phân tích các tệp XMLSchema, do đó, nó không phải là vấn đề với lược đồ hoặc mã của bạn.

Tôi chắc rằng các JRE gần đây có các lớp thích hợp theo mặc định, vì vậy bạn có thể cho chúng tôi kết quả của java -version không?


Cập nhật:

Bạn đang sử dụng chuỗi XMLContants sai. Bạn muốn: XMLConstants.W3C_XML_SCHEMA_NS_URI

+0

phiên bản java "1.6.0_17" Môi trường chạy thử Java (TM) SE (xây dựng 1.6.0_17-b04) Máy khách Java HotSpot (TM) (xây dựng 14.3-b01, chế độ hỗn hợp, chia sẻ) – Becky

+0

Tôi có cùng vấn đề, nhưng phiên bản java hệ thống của tôi "1.6.0_20" Môi trường chạy OpenJDK (IcedTea6 1.9.13) (6b20-1.9.13-0ubuntu1 ~ 10.10.1) VM máy chủ OpenJDK 64-bit (xây dựng 19.0-b09, chế độ hỗn hợp) và đang sử dụng hằng số XMLConstants.W3C_XML_SCHEMA_NS_URI, tôi vẫn nhận được lỗi ở trên (java.lang.IllegalArgumentException). xin đề nghị – candy

2

Các tệp đó dựa trên hệ thống cơ bản. Tôi đã có cùng một vấn đề khi tôi lập trình một dự án cho Android. Tôi thấy rằng tôi phải sử dụng Xerces-for-Android để giải quyết vấn đề của mình.

Sau đây làm việc cho tôi để xác nhận trên Android, nếu mã của bạn liên quan đến Android có lẽ nó sẽ giúp đỡ, nếu nó không thì có lẽ phương pháp này sẽ giúp bạn với hệ thống cơ bản của bạn:

  1. Tạo tiện ích xác thực.
  2. Nhận cả xml và xsd vào tệp trên hệ điều hành Android và sử dụng tiện ích xác thực đối với nó.
  3. Sử dụng Xerces-For-Android để thực hiện xác thực.

Android không hỗ trợ một số gói mà chúng tôi có thể sử dụng, tôi đã tạo tiện ích xác nhận xml của tôi dựa trên: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html

thử nghiệm sandbox ban đầu của tôi là khá trơn tru với java, sau đó tôi đã cố gắng đến cổng nó trên để Dalvik và thấy rằng mã của tôi không hoạt động. Một số điều không được hỗ trợ giống với Dalvik, vì vậy tôi đã thực hiện một số sửa đổi.

Tôi tìm thấy một tài liệu tham khảo để xerces for android, vì vậy tôi sửa đổi kiểm tra hộp cát của tôi (sau không làm việc với Android, ví dụ sau này không):

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

Đoạn mã trên có được sửa đổi một số để làm việc với xerces cho android (http://gc.codehum.com/p/xerces-for-android/). Bạn cần SVN để có được dự án, sau đây là một số lưu ý nôi:

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 

Với jar trên (Cuối cùng, tôi sẽ làm cho nó vào một cái lọ, chỉ cần sao chép trực tiếp vào nguồn của tôi để kiểm tra nhanh chóng.Nếu bạn muốn làm như vậy, bạn có thể làm cho jar một cách nhanh chóng với Ant (http://ant.apache.org/manual/using.html)), tôi đã có thể nhận được như sau để làm việc để xác nhận xml của tôi:

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

Một vài chú ý Side:

Đối với việc tạo ra các tập tin, tôi đã thực hiện một tiện ích tập tin đơn giản để viết chuỗi các tập tin:

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

tôi cũng cần thiết để viết thư cho một khu vực mà tôi đã truy cập vào, vì vậy tôi đã sử dụng:

String path = this.getActivity().getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.dataDir; 

Một chút hackish, nó hoạt động. Tôi chắc chắn rằng có một cách ngắn gọn hơn để làm điều này, tuy nhiên tôi figured tôi muốn chia sẻ thành công của tôi, như không có bất kỳ ví dụ tốt mà tôi tìm thấy.

Các vấn đề liên quan