程序(!)如何用wsdl验证soap请求/响应?

时间:2014-01-30 16:06:33

标签: java web-services validation soap wsdl

假设我有一个带有请求/响应和wsdl文件的xml文件。我如何通过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);
}

1 个答案:

答案 0 :(得分:0)

如果要验证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