【发布时间】:2016-07-11 18:56:21
【问题描述】:
我正在开发一个与 SOAP Web 服务交互的 Spring Java 应用程序。我们启用了对响应的严格验证(使用如下所示的拦截器),这是确保响应中不会遗漏已经商定的强制性元素所必需的。
public class MyPayloadValidatingInterceptor extends org.springframework.ws.client.support.interceptor.PayloadValidatingInterceptor{
@Override
protected boolean handleResponseValidationErrors(final MessageContext messageContext,
final SAXParseException[] errors) {
for (SAXParseException error : errors) {
this.logger.error("XML validation error in SOAP response: " + error.getMessage());
}
throw new MyResponseValidationException(errors);
}
}
这使我们的应用程序变得脆弱,即使对 SOAP Web 服务上的架构(响应的新元素)进行微小更改,并且即使我们不使用新元素,也迫使客户端升级架构,应用程序不向前兼容。 我想要一种方法来忽略响应 xml 中未识别的元素。同时对我的客户端应用程序正在使用的当前架构中的强制元素进行严格验证。
例如,如果架构是
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/Employee" xmlns:tns="http://www.example.org/Employee"
elementFormDefault="qualified">
<element name="Employee">
<complexType>
<sequence>
<element name="EmployeeId" type="string"></element>
<element name="Name" type="string"></element>
<element name="SecondName" type="string" minOccurs="0"></element>
</sequence>
</complexType>
</element>
</schema>
对于下面的 xml,我希望验证拦截器忽略未识别的元素 No MyResponseValidationException
<tns:Employee xmlns:tns="http://www.example.org/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/Employee Employee.xsd ">
<tns:EmployeeId>id</tns:EmployeeId>
<tns:Name>Jack</tns:Name>
<tns:NewElement>unidentified</tns:NewElement>
<tns:SecondName>Second Jack</tns:SecondName>
</tns:Employee>
我看到的验证错误是, cvc-complex-type.2.4.a:无效的内容是 发现以元素 'tns:NewElement' 开头。之一 '{"http://www.example.org/Employee":SecondName}' 是预期的。
对于这个 xml,它应该会导致 MyResponseValidationException
<tns:Employee xmlns:tns="http://www.example.org/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/Employee Employee.xsd ">
<tns:EmployeeId>tns:EmployeeId</tns:EmployeeId>
<!--tns:Name>tns:Name</tns:Name Mandatory Element missing-->
<tns:SecondName>tns:SecondName</tns:SecondName>
</tns:Employee>
我看到的验证错误是 cvc-complex-type.2.4.a: Invalid content was 发现以元素“tns:SecondName”开头。之一 '{"http://www.example.org/Employee":Name}' 是预期的。
您能否建议区分缺失元素和不属于架构的元素的最佳方法。
提前致谢。
【问题讨论】:
标签: java xml spring validation