【发布时间】:2016-09-08 07:26:57
【问题描述】:
我正在使用 ECCP 协议,以便将我的 CRM 与 Elastix 呼叫中心模块集成。该协议使用如下定义的 XML 结构:
<request id="1">
<request_type> <!-- this will be mapped to the Java request class -->
<attributes>
</attributes>
</request_type>
</request>
和
<response id="1">
<response_type> <!-- this will be mapped to the Java response class -->
<attributes>
</attributes>
</response_type>
</response>
我正在使用 JAX-B 将 XML 映射到 Java 类,但问题是我必须将 JAX-B 生成的 XML 放入每个请求的 <request></request> XML 中,并在每个响应中从 <response></response> 中提取内容因为 ECCP 协议定义了每个请求和响应都需要嵌套到各自的元素中。
这是我用来执行此操作的代码:
document = createDocument();
Element requestWrapper = document.createElement("request");
requestWrapper.setAttribute("id", String.valueOf(wrapped.getId()));
document.appendChild(requestWrapper);
JAXBContext jc = JAXBContext.newInstance(wrapped.getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(wrapped, requestWrapper);
举例:
ECCP 的协议操作之一是 JAX-B 映射到这样的类(省略了 getter 和 setter):
@XmlRootElement(name = "loginagent")
@XmlAccessorType(XmlAccessType.FIELD)
public class EccpLoginAgentRequest implements IEccpRequest {
@XmlElement(name = "agent_number")
private String agentNumber;
@XmlElement(name = "password")
private String password;
}
JAX-B 输出以下内容:
<loginagent>
<agent_number>username</agent_number>
<password>password</password>
</loginagent>
但是 ECCP 的协议要求的是:
<request id="1"> <!-- id is an auto-increment number to identify the request -->
<loginagent>
<username>username</username>
<password>password</password>
</loginagent>
</request>
问题是:有没有其他更好的方法可以实现? 谢谢。
【问题讨论】: