Найден ответ.
В JDK 1.7 или более поздней версии есть пакет "javax.xml.soap". Мы можем легко переключаться между двумя форматами. Нужно просто передать протокол SOAP /версия SOAP. javax.xml.soap.SOAPConstant содержит все обязательные поля констант. Вот пример кода.
package test;
import javax.xml.soap.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class SOAPGenerator {
/**
* The test namespace.
*/
public static final String NS = "http://www.test.com/xml/soap/";
/**
* Default encoding of the underlying XML in a SOAPMessage
*/
public static final String DEFAULT_ENCODING = "UTF-8";
public static void main(String[] args) {
SOAPMessage soapMessage11 = null;
SOAPMessage soapMessage12 = null;
soapMessage11 = generateSOAP("1.1");
soapMessage12 = generateSOAP("1.2");
try {
soapMessage11.writeTo(new FileOutputStream(new File("gen_soap11.xml")));
soapMessage12.writeTo(new FileOutputStream(new File("gen_soap12.xml")));
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static SOAPMessage generateSOAP(String version) {
SOAPMessage soapMsg = null;
String connectionId = "testing";
int transactionId = 1;
try {
String protocol;
if("1.1".equalsIgnoreCase(version)){
protocol = SOAPConstants.SOAP_1_2_PROTOCOL;
} else {
protocol = SOAPConstants.SOAP_1_1_PROTOCOL;
}
MessageFactory messageFactory = MessageFactory.newInstance(protocol);
soapMsg = messageFactory.createMessage();
//setting the namespace declaration.
SOAPPart sp = soapMsg.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.addNamespaceDeclaration("test", NS);
soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, DEFAULT_ENCODING);
soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
//setting the soap header.
SOAPHeader soapHeader = soapMsg.getSOAPHeader();
//setting the session id
SOAPElement soapHeaderElement1 = soapHeader.addChildElement("session", "lw", NS);
soapHeaderElement1.addTextNode(connectionId);
//setting the transactionId
SOAPElement soapHeaderElement2 = soapHeader.addChildElement("transactionId", "lw", NS);
soapHeaderElement2.addTextNode(String.valueOf(transactionId));
} catch (SOAPException e) {
e.printStackTrace();
}
return soapMsg;
}
`}