簡體   English   中英

Java XML驗證忽略不屬於模式的xml元素

[英]Java XML validation Ignore xml elements that do not belong to schema

我正在研究與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服務上對Schema(響應中的新元素)進行了微小更改,這也使我們的應用程序變得脆弱,並且即使我們不使用新元素,也迫使客戶端升級模式,應用程序不向前兼容。 我想要一種忽略響應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:發現從元素'tns:SecondName'開始的無效內容。 預期為“ {{ http://www.example.org/Employee“:Name }”之一。

您能否建議最好的方法來區分丟失的元素和不屬於架構的元素。

提前致謝。

我認為這是不可能的-您已經添加了嚴格的驗證,但是要求進行非嚴格的驗證並同時繞過未知的元素。

也許您需要添加某種

<xs:any processContents="skip" minOccurs="0"/>

在架構末尾,然后要求客戶端所有已知元素之后添加所有未知元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM