使用导入和包含在 Java 中解析模式?

Parsing Schema in Java With imports and includes?(使用导入和包含在 Java 中解析模式?)
本文介绍了使用导入和包含在 Java 中解析模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个相当复杂的 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.

我的代码如下所示:

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 中解析模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)