问题
I've been looking around the net for a good few hours now, trying to find a simple way to validate a full SOAP message against a WSDL. I am aware that there are ways to do this with the various Web Service frameworks out there, but I don't want to do this as the requirement is simply to validate a piece of XML. I could validate against the schema, although the problem I have is that there are a number of schemas imported into the WSDL and I don't know which one I should be validating against. I could write some utility to first process the WSDL and the response to determine which XSD to validate against, but I presumed this could be done as a one-liner using an established library!
Does anyone know of a relatively straightforward way to validate an XML document given a WSDL and multiple XSD's?
回答1:
In a previous project I solved this problem by parsing the WSDL-file and extracting the schemas from it. The code was something like the following, it assumes that the WSDL has been read into the Source variable "wsdlSource" in some way and that the imported namespaces are declared in the "schema"-element. It would probably be a good idea to have this performed once on startup and then do the validation in a SOAPHandler.
//First create a document from the WSDL-source
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document wsdlDoc = db.newDocument();
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(wsdlSource, new DOMResult(wsdlDoc));
//Now get the schemas from the WSDL
NodeList schemaNodes = wsdlDoc.getElementsByTagNameNS(
XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
int nrSchemas = schemaNodes.getLength();
Source[] schemas = new Source[nrSchemas];
for (int i = 0; i < nrSchemas; i++) {
schemas[i] = new DOMSource(schemaNodes.item(i));
}
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//Now we have a schema that can validate the payload
Schema schema = schemaFactory.newSchema(schemas);
Validator validator = schema.newValidator();
回答2:
There is not straight forward way for doing this. There is no open source library that I could find either. I used XML Pack tool in IBM Info sphere to do this. This does a fairly good job for importing wsdls and xsds and validating xml data or loading XML data and converting them to flat files. You may find this link useful: http://www.ibm.com/developerworks/data/library/techarticle/dm-1103datastages/index.html
来源:https://stackoverflow.com/questions/8979044/validating-soap-message-against-wsdl-with-multiple-xsds