【问题标题】:Java XML validation against XSD Schema针对 XSD Schema 的 Java XML 验证
【发布时间】:2011-01-24 17:03:33
【问题描述】:
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());
    }
}

但这会返回一个错误说: 线程“main”java.lang.IllegalArgumentException 中的异常:没有实现由 http://www.w3.org/2001/XMLSchema -instance 指定的模式语言的 SchemaFactory 可以加载

这是我的代码还是实际 xsd 文件的问题?

【问题讨论】:

    标签: java xml validation xsd


    【解决方案1】:

    这些文件基于底层系统。我在为 Android 编写项目时遇到了同样的问题。我发现我必须使用 Xerces-for-Android 来解决我的问题。

    以下方法适用于我在 Android 上的验证,如果您的代码与 Android 相关,它可能会有所帮助,如果不是,那么该方法可能会对您的底层系统有所帮助:

    1. 创建验证实用程序。
    2. 将 xml 和 xsd 都放入 android 操作系统上的文件中,然后使用验证实用程序对其进行验证。
    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 不支持某些东西,所以我做了一些修改。

    我找到了对 android 的 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;
        }
    }
    

    上面的代码必须进行一些修改才能与 xerces for android (http://gc.codehum.com/p/xerces-for-android/) 一起使用。获取项目需要SVN,以下是一些crib note:

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

    一些旁注:

    为了创建文件,我制作了一个简单的文件实用程序来将字符串写入文件:

    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;   
    

    有点hackish,它有效。我确信有一种更简洁的方法可以做到这一点,但是我想我会分享我的成功,因为我没有找到任何好的例子。

    【讨论】:

      【解决方案2】:

      该错误意味着您安装的 Java 没有任何可以解析 XMLSchema 文件的类,因此这不是架构或代码的问题。

      我很确定最近的 JRE 默认有合适的类,所以你能把java -version 的输出告诉我们吗?


      更新:

      您使用了错误的 XMLContants 字符串。你要:XMLConstants.W3C_XML_SCHEMA_NS_URI

      【讨论】:

      • java version "1.6.0_17" Java(TM) SE Runtime Environment (build 1.6.0_17-b04) Java HotSpot(TM) Client VM (build 14.3-b01,混合模式,共享)跨度>
      • 我也有同样的问题,但是我的系统 java 版本 "1.6.0_20" OpenJDK Runtime Environment (IcedTea6 1.9.13) (6b20-1.9.13-0ubuntu1~10.10.1) OpenJDK 64-Bit服务器 VM(构建 19.0-b09,混合模式),并且正在使用 XMLConstants.W3C_XML_SCHEMA_NS_URI 常量,但我仍然遇到错误(java.lang.IllegalArgumentException)。请建议
      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2011-10-12
      • 2011-07-18
      相关资源
      最近更新 更多