我有
两个XSD文件都有一个命名空间。
文件3)包括文件2):<xs:include schemaLocation="someschema.xsd"></xs:include>
XML文档(文件1)具有以下根标记:
<tagDefinedInSchema xmlns="http://myurl.com/myapp/myschema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://myurl.com/myapp/myschema schemaFile2.xsd">
其中schemaFile2.xsd
是上面的文件3.
我需要针对两个模式验证文件1,而不需要
修改文件本身和
在一个文件中合并两个模式。
我怎样才能用Java做到这一点?
UPD:这是我正在使用的代码。
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
documentFactory.setNamespaceAware(namespaceAware);
DocumentBuilder builder = documentFactory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xmlData
.getBytes("UTF-8")));
File schemaLocation = new File(schemaFileName);
Schema schema = schemaFactory.newSchema(schemaLocation);
Validator validator = schema.newValidator();
Source source = new DOMSource(document);
validator.validate(source);
UPD 2:这对我有用:
public static void validate(final String xmlData,
final String schemaFileName, final boolean namespaceAware)
throws SAXException, IOException {
final SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new MySchemaResolver());
final Schema schema = schemaFactory.newSchema();
final Validator validator = schema.newValidator();
validator.setResourceResolver(schemaFactory.getResourceResolver());
final InputSource is = new InputSource(new ByteArrayInputStream(xmlData
.getBytes("UTF-8")));
validator.validate(new SAXSource(is), new SAXResult(new XMLReaderAdapter()));
}
class MySchemaResolver implements LSResourceResolver {
@Override
public LSInput resolveResource(final String type,
final String namespaceURI, final String publicId, String systemId,
final String baseURI) {
final LSInput input = new DOMInputImpl();
try {
if (systemId == null) {
systemId = SCHEMA1;
}
FileInputStream fis = new FileInputStream(
new File("path_to_schema_directory/" + systemId));
input.setByteStream(fis);
return input;
} catch (FileNotFoundException ex) {
LOGGER.error("File Not found", ex);
return null;
}
}
}
答案 0 :(得分:2)
一些术语:这里有一个模式,它是从两个模式文档构建的。
如果在构建Schema时为API指定了schemaFile2.xsd,它应该通过xs:include自动引入其他文档。如果您怀疑这种情况没有发生,您需要解释导致您相信这些症状的原因。
答案 1 :(得分:0)
看起来效率可能有点低,但是你不能对模式A进行验证,使用模式B创建一个新的验证器并对其进行验证吗?