Java 根据多个架构定义验证 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1094893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:38:49  来源:igfitidea点击:

Validate an XML File Against Multiple Schema Definitions

javaxsdxerces

提问by Jon

I'm trying to validate an XML file against a number of different schemas (apologies for the contrived example):

我正在尝试针对许多不同的模式验证 XML 文件(对人为示例表示歉意):

  • a.xsd
  • b.xsd
  • c.xsd
  • 一个.xsd
  • b.xsd
  • c.xsd

c.xsd in particular imports b.xsd and b.xsd imports a.xsd, using:

c.xsd 特别是进口 b.xsd 和 b.xsd 进口 a.xsd,使用:

<xs:include schemaLocation="b.xsd"/>

<xs:include schemaLocation="b.xsd"/>

I'm trying to do this via Xerces in the following manner:

我正在尝试通过 Xerces 以下列方式执行此操作:

XMLSchemaFactory xmlSchemaFactory = new XMLSchemaFactory();
Schema schema = xmlSchemaFactory.newSchema(new StreamSource[] { new StreamSource(this.getClass().getResourceAsStream("a.xsd"), "a.xsd"),
                                                         new StreamSource(this.getClass().getResourceAsStream("b.xsd"), "b.xsd"),
                                                         new StreamSource(this.getClass().getResourceAsStream("c.xsd"), "c.xsd")});     
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new StringReader(xmlContent)));

but this is failing to import all three of the schemas correctly resulting in cannot resolve the name 'blah' to a(n) 'group' component.

但这无法正确导入所有三个模式,导致无法将名称“blah”解析为(n)“group”组件。

I've validated this successfully using Python, but having real problems with Java 6.0and Xerces 2.8.1. Can anybody suggest what's going wrong here, or an easier approach to validate my XML documents?

我已经使用Python成功验证了这一点,但在使用Java 6.0Xerces 2.8.1 时遇到了实际问题。任何人都可以建议这里出了什么问题,或者更简单的方法来验证我的 XML 文档?

采纳答案by Jon

So just in case anybody else runs into the same issue here, I needed to load a parent schema (and implicit child schemas) from a unit test - as a resource - to validate an XML String. I used the Xerces XMLSchemFactory to do this along with the Java 6 validator.

因此,以防万一其他人在这里遇到相同的问题,我需要从单元测试加载父模式(和隐式子模式)——作为资源——来验证 XML 字符串。我使用 Xerces XMLSchemFactory 和 Java 6 验证器来执行此操作。

In order to load the child schema's correctly via an include I had to write a custom resource resolver. Code can be found here:

为了通过包含正确加载子模式,我必须编写一个自定义资源解析器。代码可以在这里找到:

https://code.google.com/p/xmlsanity/source/browse/src/com/arc90/xmlsanity/validation/ResourceResolver.java

https://code.google.com/p/xmlsanity/source/browse/src/com/arc90/xmlsanity/validation/ResourceResolver.java

To use the resolver specify it on the schema factory:

要使用解析器在架构工厂上指定它:

xmlSchemaFactory.setResourceResolver(new ResourceResolver());

and it will use it to resolve your resources via the classpath (in my case from src/main/resources). Any comments are welcome on this...

它将使用它通过类路径(在我的情况下来自 src/main/resources)解析您的资源。欢迎对此提出任何意见...

回答by skaffman

The schema stuff in Xerces is (a) very, very pedantic, and (b) gives utterly useless error messages when it doesn't like what it finds. It's a frustrating combination.

Xerces 中的模式内容 (a) 非常非常迂腐,并且 (b) 当它不喜欢它发现的内容时会给出完全无用的错误消息。这是一个令人沮丧的组合。

The schema stuff in python may be a lot more forgiving, and was letting small errors in the schema go past unreported.

python 中的模式内容可能要宽容得多,并且让模式中的小错误没有被报告。

Now if, as you say, c.xsd includes b.xsd, and b.xsd includes a.xsd, then there's no need to load all three into the schema factory. Not only is it unnecessary, it will likely confuse Xerces and result in errors, so this may be your problem. Just pass c.xsd to the factory, and let it resolve b.xsd and a.xsd itself, which it should do relative to c.xsd.

现在,如果如您所说,c.xsd 包含 b.xsd,而 b.xsd 包含 a.xsd,则无需将所有三个加载到模式工厂中。它不仅没有必要,而且可能会混淆 Xerces 并导致错误,因此这可能是您的问题。只需将 c.xsd 传递给工厂,让它自己解析 b.xsd 和 a.xsd,它应该相对于 c.xsd 来做。

回答by iolha

http://www.kdgregory.com/index.php?page=xml.parsingsection 'Multiple schemas for a single document'

http://www.kdgregory.com/index.php?page=xml.parsing部分'单个文档多个模式'

My solution based on that document:

我基于该文件的解决方案:

URL xsdUrlA = this.getClass().getResource("a.xsd");
URL xsdUrlB = this.getClass().getResource("b.xsd");
URL xsdUrlC = this.getClass().getResource("c.xsd");

SchemaFactory schemaFactory = schemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//---
String W3C_XSD_TOP_ELEMENT =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
   + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">\n"
   + "<xs:include schemaLocation=\"" +xsdUrlA.getPath() +"\"/>\n"
   + "<xs:include schemaLocation=\"" +xsdUrlB.getPath() +"\"/>\n"
   + "<xs:include schemaLocation=\"" +xsdUrlC.getPath() +"\"/>\n"
   +"</xs:schema>";
Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(W3C_XSD_TOP_ELEMENT), "xsdTop"));

回答by Hesse

From the xerces documentation : http://xerces.apache.org/xerces2-j/faq-xs.html

来自 xerces 文档:http: //xerces.apache.org/xerces2-j/faq-xs.html

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;

...

StreamSource[] schemaDocuments = /* created by your application */;
Source instanceDocument = /* created by your application */;

SchemaFactory sf = SchemaFactory.newInstance(
    "http://www.w3.org/XML/XMLSchema/v1.1");
Schema s = sf.newSchema(schemaDocuments);
Validator v = s.newValidator();
v.validate(instanceDocument);

回答by Edenshaw

I ended up using this:

我最终使用了这个:

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
 .
 .
 .
 try {
        SAXParser parser = new SAXParser();
        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/validation/schema-full-checking", true);
        parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "http://your_url_schema_location");

        Validator handler = new Validator();
        parser.setErrorHandler(handler);
        parser.parse("file:///" + "/home/user/myfile.xml");

 } catch (SAXException e) {
    e.printStackTrace();
 } catch (IOException ex) {
    e.printStackTrace();
 }


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

Remember to change:

记得改:

1) The parameter "http://your_url_schema_location"for you xsd file location.

1) 参数“http://your_url_schema_location”为您的 xsd 文件位置。

2) The string "/home/user/myfile.xml"for the one pointing to your xml file.

2)指向您的 xml 文件的字符串“/home/user/myfile.xml”

I didn't have to set the variable: -Djavax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema=org.apache.xerces.jaxp.validation.XMLSchemaFactory

我不必设置变量: -Djavax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema=org.apache.xerces.jaxp.validation.XMLSchemaFactory

回答by Weslor

I faced the same problem and after investigating found this solution. It works for me.

我遇到了同样的问题,经过调查找到了这个解决方案。这个对我有用。

Enumto setup the different XSDs:

Enum设置不同的XSDs

public enum XsdFile {
    // @formatter:off
    A("a.xsd"),
    B("b.xsd"),
    C("c.xsd");
    // @formatter:on

    private final String value;

    private XsdFile(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }
}

Method to validate:

验证方法:

public static void validateXmlAgainstManyXsds() {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    String xmlFile;
    xmlFile = "example.xml";

    // Use of Enum class in order to get the different XSDs
    Source[] sources = new Source[XsdFile.class.getEnumConstants().length];
    for (XsdFile xsdFile : XsdFile.class.getEnumConstants()) {
        sources[xsdFile.ordinal()] = new StreamSource(xsdFile.getValue());
    }

    try {
        final Schema schema = schemaFactory.newSchema(sources);
        final Validator validator = schema.newValidator();
        System.out.println("Validating " + xmlFile + " against XSDs " + Arrays.toString(sources));
        validator.validate(new StreamSource(new File(xmlFile)));
    } catch (Exception exception) {
        System.out.println("ERROR: Unable to validate " + xmlFile + " against XSDs " + Arrays.toString(sources)
                + " - " + exception);
    }
    System.out.println("Validation process completed.");
}

回答by Shafiul

Just in case, anybody still come here to find the solution for validating xml or object against multiple XSDs, I am mentioning it here

以防万一,仍然有人来这里寻找针对多个 XSD 验证 xml 或对象的解决方案,我在这里提到它

//Using **URL** is the most important here. With URL, the relative paths are resolved for include, import inside the xsd file. Just get the parent level xsd here (not all included xsds).

URL xsdUrl = getClass().getClassLoader().getResource("my/parent/schema.xsd");

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdUrl);

JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);

/* If you need to validate object against xsd, uncomment this
ObjectFactory objectFactory = new ObjectFactory();
JAXBElement<MyClass> wrappedObject = objectFactory.createMyClassObject(myClassObject); 
marshaller.marshal(wrappedShipmentMessage, new DefaultHandler());
*/

unmarshaller.unmarshal(getClass().getClassLoader().getResource("your/xml/file.xml"));