gpt4 book ai didi

java - 将 JAXB 元素编码为 SOAP 处理转义字符

转载 作者:行者123 更新时间:2023-12-02 10:38:21 26 4
gpt4 key购买 nike

我正在尝试将 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>&lt;![CDATA[Hel..&lt;..lo]]&gt;</payload><age>29</age><name>Hel..&lt;..lo</name></customer>
</SOAP-ENV:Body></SOAP-ENV:Envelope>

最佳答案

我通过使用 jaxbMarshaller 修复了这个问题,如下所示

 jaxbMarshaller.marshal(elem, soapBody);

其中elemJAXBElement

关于java - 将 JAXB 元素编码为 SOAP 处理转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53108851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com