最近调试要求xml报文交互项目,之前就应用过Jaxb来处理object互转xml,只是此次项目中接口报文较多,且相似,所以将过去的代码要重新封装重构下。
如下报文,外层不变,只有body内容不固定,所以用到泛型加以控制:
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<Request>
<Head>
<Version>Version</Version>
<orgId>orgId</CertId>
</Head>
<Body>
<infoList>
<info>
<name>name</name>
<dept>dept</dept>
</info>
<info>
<name>111111111</name>
</info>
</infoList>
</Body>
</Request>
</Document>
实体Document
package com.test;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"request"
})
@XmlRootElement(name = "Document")
public class Document {
@XmlElements({
@XmlElement(name = "Request", type = com.test.intfc.Request.class)
})
protected BaseRequest<? extends BaseBody> request;
setter()/getter()
}
实体BaseRequest
package com.test;
@XmlTransient
public abstract class BaseRequest<T extends BaseBody> {
protected Head head;
protected T body;
public abstract Head getHead();
public abstract void setHead(Head value);
public abstract T getBody();
public abstract void setBody(T value);
}
实体Head ......略
实体Basebody
package com.test;
@XmlTransient
public abstract class BaseBody {}
实体Request
package com.test.intfc;
@XmlRootElement(name = "Request")
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "", propOrder = { "head", "body" })
public class Request extends BaseRequest<Body> {
@XmlElement(name = "Head", required = true)
@Override
public Head getHead() {
return head;
}
@Override
public void setHead(Head value) {
this.head = value;
}
@XmlElement(name = "Body", required = true)
@Override
public Body getBody() {
return body;
}
@Override
public void setBody(Body value) {
this.body = value;
}
}
实体Body
package com.test.intfc;
@XmlRootElement(name = "Body")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"dept"
})
public class Body extends BaseBody {
// 简写....
@XmlElement(name = "name", required = true)
protected String name;
@XmlElement(name = "dept", required = true)
protected String dept;
...setter()/getter()
}
测试
package com.test;
public class Test {
public static void main(String[] args) {
......
Request req = new Request();
Document doc = new Document();
doc.setRequest(req);
JaxbBinder reqBinder = new JaxbBinder(Document.class);
String xmlReq = reqBinder.toXml(doc, true);
}
}
JaxbBinder从网上搜,一堆堆的例子。。。。
xml --> xsd --> Object 方式快速生成的
命令如:$ xjc -d . -p com.test ./example.xsd
生成的Object实体需要自己按上面的修改,注意“@注解”的应用,否则将报异常:[javax.xml.bind.JAXBException:类 org.test.******。或其任何超类是 已知此上下文。]