有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当模式文件位于WAR中时,针对XSD的java XML验证

我试图根据多个XSD模式验证XML

如果我将我的应用程序作为一个简单的Spring Boot应用程序执行,那么下面的代码就像一个符咒:

// init
String[] xsdFileNames = ...
Source[] sources = new Source[xsdFileNames.length];

for (int i = 0; i < xsdFileNames.length; i++) {
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdFileNames[i]);
    String realPath = getClass().getClassLoader().getResource(xsdFileNames[i]).getFile();

    StreamSource streamSource = new StreamSource(inputStream);
    streamSource.setSystemId(realPath );

    sources[i] = streamSource;
}

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(sources);
validator = schema.newValidator();

// validate
String xmlString = ...
StringReader xmlStringReader = new StringReader(xmlString))
Source source = new StreamSource(xmlStringReader);
validator.validate(source);

需要设置StreamSourcesystemId,否则SAXParser无法看到来自第二个XSD的XSD类型。更多信息here

但不幸的是,我的WAR需要在Oracle WebLogic服务器上运行,而且由于WebLogic对来自WAR的文件进行了欺骗,因此上述解决方案不起作用

WebLogic将资源文件打包到_wl_cls_gen.jar中,并且javax.xml.transform.Source无法使用此神奇jar解析路径:.../_wl_cls_gen.jar!/schema/main.xsd

javax.xml.transform.Source里面有一个java.io.File并且它没有沿着这个奇怪的路径走

这是Spring启动时realPath变量的值:

/home/xxx/dev/workspace/java/xxx/target/classes/schema/main.xsd

对于WebLogic:

/u01/oracle/user_projects/domains/DEV_DOMAIN/servers/ADMIN_SERVER/tmp/_WL_user/demo-0.1.0/g369dl/war/WEB-INF/lib/_wl_cls_gen.jar!/schema/main.xsd

你知道怎么处理吗


共 (2) 个答案

  1. # 1 楼答案

    您可以从*中加载文件。war使用类加载器,例如

    getClass().getClassLoader().getResourceAsStream("/resources/myfile.xsd");
    
  2. # 2 楼答案

    尝试使用weblogic中启用的显示存档实路径。xml

    show-archived-real-path-enabled The show-archived-real-path-enabled element specifies the behavior of getRealPath() for archived Web applications.

    When set to true, getRealPath() returns the canonical path of the resource files.

    If the show-archived-real-path-enabled element is set to false, the servlet container will return the real path of files in archived Web applications as null.

    The default value is false.

    https://docs.oracle.com/cd/E24329_01/web.1211/e21049/weblogic_xml.htm#WBAPP611