[英]JAXB. Validating XML by two xsd
Does it possible to validate xml while unmarshaling by two xsd? 是否可以在通过两个xsd编组时验证xml? I know that you unmarshal xml to object with several contexts by doing this:
我知道您通过执行以下操作将xml解组到具有多个上下文的对象:
context = JAXBContext.newInstance("onepackagecontext:secondpackagecontext");
I can use one schema for validation: 我可以使用一种模式进行验证:
unmarshaller.setSchema(getSchema(url));
What could I do so that use two XSD for validation? 我该怎么做才能使用两个XSD进行验证?
You can do like this: 你可以这样做:
final InputStream isMain = this.getClass().getResourceAsStream( "/real.xsd" );
final InputStream isImport=
this.getClass().getResourceAsStream( "/import.xsd" );
final InputStream isInclude =
this.getClass().getResourceAsStream( "/include.xsd" );
final Source include = new StreamSource( isInclude );
final Source imp = new StreamSource( isImport );
final Source main = new StreamSource( isMain );
final Source[] schemaFiles = new Source[] {
include, imp, main
};
final SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
final Schema schema = sf.newSchema( schemaFiles );
final JAXBContext jc =
JAXBContext.newInstance( YourJaxb.class );
final Unmarshaller unmarshaller = jc.createUnmarshaller();
final JAXBElement<YourJaxb> jaxbElement =
unmarshaller.unmarshal(
YourJaxb.class );
final JAXBSource source = new JAXBSource( jc, jaxbElement.getValue() );
final ValidationErrorHandler val = new ValidationErrorHandler();
final Validator validator = schema.newValidator();
validator.setErrorHandler( val );
validator.validate( source );
I don't see a reason why this should work. 我看不出这应该起作用的原因。 If there is no relation between the two schemas, this can be problematic
如果两个模式之间没有关系,则可能会出现问题
If you take a look for example at generation of Java classes from XSD - if you provide two unrelated XSDs to the generator, it may cause an attempt to create mutliple inheritance and issues like that. 如果您看一下从XSD生成Java类的情况-如果您向生成器提供两个不相关的XSD,则可能会导致尝试创建多重继承和类似问题。 I suspect you might have some bad design here
我怀疑你这里的设计可能不好
What I do suggest is that you revisit the schemas , and see how you can unify them to one schema that will answer you needs. 我建议您重新访问这些架构,并了解如何将它们统一为一个可以满足您需求的架构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.