使用具有嵌套导入的架构来验证Java中的XML

问题描述

我正在尝试使用嵌套导入针对xsd模式验证XML字符串:

types.xsd

<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/types" xmlns:gef="http://www.example.com/geofencing">
  <xsd:import namespace="http://www.example.com/implementations" schemaLocation="implementationsV2.1.xsd"/>  
  <xsd:element name="geofencingMode">
    <xsd:complexType>
      <xsd:attribute name="mode" type="gef:modeId"/>
      <xsd:attribute name="period" type="gef:periodId"/>
    </xsd:complexType>
  </xsd:element>
</schema>

implementationsV2.1.xsd

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://www.example.com/implementations" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:import namespace="http://www.example.com/geofencing" schemaLocation="geofencingServiceV2.1.xsd">
        <xsd:annotation>
            <xsd:documentation>...</xsd:documentation>
        </xsd:annotation>
    </xsd:import>
</schema>

geofencingServiceV2.1.xsd

<xsd:schema targetNamespace="http://www.example.com/geofencing"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://www.example.com/geofencing">
    <xsd:simpleType name="modeId">
        ...
    </xsd:simpleType>
</schema>

具有以下验证代码

private void validateResponseSchema(String response) throws IOException,SAXException {
  SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema = factory.newSchema(new ClassPathResource("types.xsd").getURL());
  Validator validator = schema.newValidator();
  validator.validate(new StreamSource(new ByteArrayInputStream(response.getBytes())));
}

我得到了错误

org.xml.sax.SAXParseException; systemId: file:/.../types.xsd; lineNumber: 358; columnNumber: 87; src-resolve.4.2: Error resolving component 'gef:modeId'.
  It was detected that 'gef:modeId' is in namespace 'http://www.example.com/geofencing',but components from this namespace are not referenceable from schema document 'file:/.../types.xsd'.
  If this is the incorrect namespace,perhaps the prefix of 'gef:modeId' needs to be changed. If this is the correct namespace,then an appropriate 'import' tag should be added to 'file:/.../types.xsd'.

如果我直接在geofencing中导入types.xsd命名空间,则可以使用,但是我不明白为什么需要这样做。

  • 我在此处包括一个命名空间,但implementations中存在多个命名空间
  • 我无法轻易修改要验证的xsds
  • 通过调试,我可以确认链接文件已正确解析

是否有一个选项也许我会丢失?该错误似乎特定于引擎盖下使用的Java库(Apache xerces),因为该模式否则有效。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...