在php小编草莓的指导下,我们将探讨使用作为文件加载的xsd进行xml验证与输入流的方法。当我们处理xml数据时,验证是非常重要的一步,以确保数据的正确性和完整性。通过使用xsd(xml schema definition)文件,我们可以定义xml文档的结构和约束。通过加载xsd文件并将其用于验证输入的xml流,我们可以轻松地检测和处理不符合规定的数据,从而提高应用程序的可靠性和安全性。接下来,我们将详细介绍如何使用xsd文件进行xml验证和输入流处理。
如果 xsd 作为文件或资源加载,我在 xml 验证中会遇到不同的行为。
如果我将 xsd 作为文件加载,一切都很好并且验证工作正常:
schemafactory sf = schemafactory.newinstance(xmlconstants.w3c_xml_schema_ns_uri);
schema schema = sf.newschema(new classpathresource("my/perfect/path/myfile.xsd").getfile());
validator validator = schema.newvalidator();
validator.validate(sourcetovalidate);相反,因为我决定将 xsd 文件包含到 jar 中,所以我将其作为资源加载,但行为不同,当我构造架构时,我陷入 saxparseexception ,并且错误抱怨中的某些问题将 xsd 文件中的名称解析为类型定义。 xsd 文件绝对正确
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("my/perfect/path/myFile.xsd");
Source schemaSource = new StreamSource(inputStream);
Schema schema = sf.newSchema(schemaSource); // here i get the SAXParseException
Validator validator = schema.newValidator();
validator.validate(sourceToValidate);我真的不明白为什么加载 xsd 作为 resourceasstream 会导致不同的行为
我使用 jaxb 进行 xml 验证
我猜测您的 xsd 引用了其他 xsd,并且您的验证器不知道如何解析这些引用。
您可能需要提供 lsresourceresolver 到 validator
classloader loader = getclass().getclassloader();
lsresourceresolver resolver = new lsresourceresolver() {
public lsinput resolveresource(string type, string namespaceuri, string publicid, string systemid, string baseuri) {
inputstream stream = loader.getresourceasstream(systemid);
if (stream == null) throw new runtimeexception("could not find " + systemid);
lsinput input = new dominputimpl();
input.setpublicid(publicid);
input.setsystemid(systemid);
input.setbaseuri(baseuri);
input.setbytestream(stream);
return input;
}
};
validator validator = schema.newvalidator();
validator.setresourceresolver(resolver);
您还需要通过调用 streamsource 的两个参数构造函数来在 inputsource 上设置 systemid。
String xsdPath = "my/perfect/path/myFile.xsd"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xsdPath); Source schemaSource = new StreamSource(inputStream, xsdPath);
请参阅streamsource(inputstream, string)
以上就是使用作为文件加载的 XSD 进行 XML 验证与输入流的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号