用Java解析Schema使用import和includes? [英] Parsing Schema in Java With imports and includes?

查看:205
本文介绍了用Java解析Schema使用import和includes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个相当复杂的XML模式解析为Java中的Schema对象,因此我可以对XML消息进行一些验证。

I'm attempting to parse load a rather complicated XML schema into a Schema object in Java so I can do some validation on XML messages.

我的代码看起来类似对此:

My code looks similar to this:

SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new File("schema/schema.xsd")));

我的架构有很多进口:

<?xml version="1.0" encoding="UTF-8"?>
  <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="base_1">
  <xs:import namespace="base_1" schemaLocation="common/MessageBase.xsd"/>
</xs:schema>

...等。当我尝试加载架构时,我遇到了很多错误。基于与此相关的另一个问题,看起来我需要指定一个资源解析器,但是这不是应该默认处理的东西吗?

...etc. When I attempt to load the schema, I get lots of errors. Based on one other question related to this, it looks like I need to specify a resource resolver, but isn't this something that should be handled by default?

如果是这样的话,是否有一个特定的目录,我需要将模式放在相对于我正在编写的应用程序或相对于基本模式文件的位置?

If so, is there a specific directory I need to put the schema in relative to where I run the application I'm writing or relative to the base schema file?

最后,当我使用XMLSpy或类似方法加载模式,它工作正常,我可以毫无问题地验证XML实例。

Finally, when I load the schema with XMLSpy or similar, it works fine and I can validate XML instances with no problem.

推荐答案

我认为使用StreamSource而不指定基本位置是问题的根源。

I think that the use of StreamSource, without specifying the base location, is the source of your problem.

解析器无法知道主模式的位置,因此可以'解决common / MessageBase.xml。

The parser has no way of knowing where the main schema is, so it can't resolve common/MessageBase.xml.

使用双参数构造函数并传入一个SystemID,它是您开始的路径名。

Use the two-argument constructor and pass in a SystemID that is the pathname where you're starting from.

请参阅StreamSource的javadoc。

See the javadoc for StreamSource.

这篇关于用Java解析Schema使用import和includes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆