【问题标题】:Example to validate a xml-File against an XSD v1.1 Schema in Java 1.8在 Java 1.8 中针对 XSD v1.1 模式验证 xml 文件的示例
【发布时间】:2016-06-26 18:43:54
【问题描述】:
  • 我当前的验证不适用于 XSD v1.1 Schemas .. 我尝试了很多方法来改变它,但直到现在都没有成功
  • 解决方案是用 Saxon 还是 Xerces 完成对我来说并不重要(编辑:我不想花钱来解决问题,而且看起来 Saxon XSD1.1 验证不是免费的,所以我想我有坚持使用 Xerces)
  • 是的,我已经为此搜索过 SO,但到目前为止,没有任何 code-sn-ps 帮助我获得有效的验证。
  • 代码将用于 Eclipse 插件,如果这很重要的话
  • 我将以下 jar 文件添加到项目/类路径中,但它似乎没有在我的代码中使用:
<dependency>
  <groupId>xerces</groupId>
  <artifactId>xercesImpl</artifactId>
  <version>2.11.0</version>
</dependency>

这里是我目前用于验证的代码(如果不能用于 xsd1.1,则转储它没有问题):

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.xni.parser.XMLInputSource;

....

public List<MyError> validate(File xmlFile) {
    List<MyError> errors = null;
    try {
        DOMParser parser = new DOMParser();
        parser.setFeature(XmlUtils.VALIDATION, true);
        parser.setFeature(XmlUtils.VALIDATION_SCHEMA, true);
        parser.setFeature(XmlUtils.ALL_SCHEMA_LOCATIONS, true);
        parser.setFeature(XmlUtils.DEFER_NODE_EXPANSION, false);

        Handler handler = new Handler(xmlFile, parser);
        parser.setErrorHandler(handler);

        // there probably are smarter ways to do this
        String uri = xmlFile.toURI().toString().replace("%20", " ");
        InputStream inputStream = new FileInputStream(xmlFile);
        XMLInputSource inputSource = new XMLInputSource("", uri, uri, inputStream, "UTF-8");
        parser.parse(inputSource);

        errors = handler.getErrors();

    }
    catch (Exception e)
    {
        ConsoleHandler.printError("Document " + xmlFile.getName() + " has not been parsed correctly: " + e.getMessage(), true);
        ConsoleHandler.printStackTrace(e);
    }
    // printing the errors happens in some other method
    return errors;
}

【问题讨论】:

    标签: java xsd-validation xerces xsd-1.1


    【解决方案1】:

    您已标记此“Saxon”,因此我假设您正在寻找 Saxon 解决方案。 (但您也将其标记为“Xerces”)。您已经显式地实例化了 Xerces DOMParser,因此这里没有任何东西可以调用 Saxon 作为模式验证器。如果您想要 Xerces 解决方案,那么我不是专家,无法帮助您。如果您需要 Saxon 解决方案,您会在 saxon-resources 下载文件(SourceForge 和 saxonica.com 上都提供)中找到大量示例。以下是一些大致可以满足您需求的摘录:

    s9api 示例:

                Processor proc = new Processor(true);
                SchemaManager sm = proc.getSchemaManager();
                sm.load(new StreamSource(new File("data/books.xsd")));
    
                try {
                    SchemaValidator sv = sm.newSchemaValidator();
                    sv.validate(new StreamSource(new File("data/books.xml")));
                    System.out.println("First schema validation succeeded (as planned)");
                } catch (SaxonApiException err) {
                    System.out.println("First schema validation failed");
                }
    

    JAXP 示例:

                System.setProperty("javax.xml.transform.TransformerFactory",
                                   "com.saxonica.config.EnterpriseTransformerFactory");
                TransformerFactory factory = TransformerFactory.newInstance();
                System.err.println("TransformerFactory class: " + factory.getClass().getName());
                factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, new Integer(Validation.STRICT));
                factory.setAttribute(FeatureKeys.VALIDATION_WARNINGS, Boolean.TRUE);
                if (args.length > 1) {
                    StreamSource schema = new StreamSource(new File(args[1]).toURI().toString());
                    ((EnterpriseTransformerFactory)factory).addSchema(schema);
                }
                Transformer trans = factory.newTransformer();
                StreamSource source = new StreamSource(new File(args[0]).toURI().toString());
                SAXResult sink = new SAXResult(new DefaultHandler());
                trans.transform(source, sink);
    

    【讨论】:

    • 感谢您的回复!撒克逊解决方案对我来说很好,我不需要坚持使用 Xerces。我会尽快测试它。为了完成(随意添加):示例例如可以在这里找到:saxonica.com/html/documentation/schema-processing/…
    • 看起来没有免费提供的 Saxon XSD1.1 验证器:“Saxon-EE(企业版)是功能齐全的商业产品。Saxon-EE 9.7 提供......作为完全符合 XSD 1.0 和 XSD 1.1 模式的处理器,并且......”因为我不想花钱购买 XSD1.1 验证器(添加到帖子 #1),所以我怀疑我不能使用 Saxon,对吗?
    • 是的,没错,Saxon 模式验证器将为第一个用户支付 90 英镑,为后续用户支付 60 英镑。
    【解决方案2】:

    好的,我终于让我的 XML 能够通过 Xerces 对照 XSD1.1 Schema 进行验证。这里是我使用的依赖:

    <dependency>
        <groupId>org.opengis.cite.xerces</groupId>
        <artifactId>xercesImpl-xsd11</artifactId>
        <version>2.12-beta-r1667115</version>
    </dependency>
    

    (似乎还没有支持 xsd1.1 的官方 xerces 版本。首先让我感到困惑的是:Xercex v2.11.0 似乎不支持 XSD1.1,而 2.11.0.beta 支持)

    这里是我使用的源代码:

    import java.io.File;
    import java.io.IOException;
    
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    
    import org.xml.sax.SAXException;
    
    public class MyClass {
    
        public static void main(String[] args) {
    
            try {
                validateFile(new File("Test.xml") , new  File("Test.xsd"));
            } catch (Exception e) {
    
                e.printStackTrace();
            }
        }
    
        private static void validateFile(File xmlFile, File xsdFile) throws SAXException, IOException
        {
            SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
            File schemaLocation = xsdFile;
            Schema schema = factory.newSchema(schemaLocation);
            Validator validator = schema.newValidator();
            Source source = new StreamSource(xmlFile);
            try
            {
                validator.validate(source);
                System.out.println(xmlFile.getName() + " is valid.");
            }
            catch (SAXException ex)
            {
                System.out.println(xmlFile.getName() + " is not valid because ");
                System.out.println(ex.getMessage());
            }
        }
    }
    

    编辑:但是我的代码还没有作为 eclipse-plugin 运行。在插件中触发验证时,我收到以下错误:

    !ENTRY org.eclipse.core.jobs 4 2 2016-03-15 15:14:37.852
    !MESSAGE An internal error occurred during: "validation job".
    !STACK 0
    javax.xml.validation.SchemaFactoryConfigurationError: Provider for class javax.xml.validation.SchemaFactory cannot be created
        at javax.xml.validation.SchemaFactoryFinder.findServiceProvider(SchemaFactoryFinder.java:414)
        at javax.xml.validation.SchemaFactoryFinder._newFactory(SchemaFactoryFinder.java:218)
        at javax.xml.validation.SchemaFactoryFinder.newFactory(SchemaFactoryFinder.java:145)
        at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:213)
        at plugin.control.validation.MyValidator.validateFile(MyValidator.java:39)
        at
    ...
    

    引发异常的代码行:

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 2011-01-24
      • 2013-09-05
      • 2012-12-01
      • 2011-02-07
      • 2014-07-13
      • 1970-01-01
      相关资源
      最近更新 更多