Web Services 如何用wsdl以编程方式(!)验证soap请求/响应?

e5njpo68  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(172)

假设我有一个xml文件,其中包含请求/响应和wsdl文件。我如何通过wsdl验证 * 请求/响应 *?

重要提示

我知道可以使用Spring-Ws或Metro等容器来启用这种验证,但我希望在没有这样容器的情况下进行手动验证:

public static void main (String[] arg) {
     File xmlRequest = new File(arg[0]);
     File wsdlFile = new File(arg[1]);
     //....
     someValidator.validate(xmlRequest, wsdlFile);
}
vof42yt1

vof42yt11#

如果要验证xml,则需要为该xml创建XSD。
在此之后,就像您所做的那样,只需要调用validate方法。

package com.journaldev.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class XMLValidation {

    public static void main(String[] args) {

      System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));
      System.out.println("EmployeeResponse.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));
      System.out.println("employee.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "employee.xml"));

      }

    public static boolean validateXMLSchema(String xsdPath, String xmlPath){

        try {
            SchemaFactory factory = 
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(xmlPath)));
        } catch (IOException | SAXException e) {
            System.out.println("Exception: "+e.getMessage());
            return false;
        }
        return true;
    }
}

这里有一个教程:

http://www.journaldev.com/895/how-to-validate-xml-against-xsd-in-java

相关问题