【发布时间】:2018-11-01 20:24:26
【问题描述】:
我正在尝试将 JAXB 元素编组到 SOAPBody 包装器中,我能够转义 JAXB 中的编码字符,但是当我将其编组到 SOAP 文档中时,它并没有转义这些 xml 字符。任何帮助。提前致谢。
而且我的项目很小,我们没有使用任何外部包,尝试在开放 jdk 中执行此操作。
package test;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;
public class JAXBExample {
public static void main(String[] args) throws SOAPException, IOException {
Customer customer = new Customer();
customer.setId(100);
customer.setName("Hel..<..lo");
customer.setAge(29);
try {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// jaxbMarshaller.setProperty(CharacterEscapeHandler.class.getName(), new CustomCharacterEscapeHandler());
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.characterEscapeHandler",
new CharacterEscapeHandler() {
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer writer)
throws IOException {
writer.write(ch, start, length);
}
});
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.marshal(customer, System.out);
jaxbMarshaller.marshal(customer, soapBody);
soapMessage.saveChanges();
soapMessage.writeTo(System.out);
}
catch (JAXBException e) {
e.printStackTrace();
}
}
}
// result just with jaxb ***
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<payload><![CDATA[Hel..<..lo]]></payload>
<age>29</age>
<name>Hel..<..lo</name>
</customer>
// result jaxb wrapped into SOAPbody***
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/>
<SOAP-ENV:Body>
<customer id="100">
<payload><![CDATA[Hel..<..lo]]></payload><age>29</age><name>Hel..<..lo</name></customer>
</SOAP-ENV:Body></SOAP-ENV:Envelope>
【问题讨论】:
标签: java soap encoding jaxb saaj