Java把一个对象转换成xml数据
使用jdk自带注解在一个实体类上添加注解@XmlRootElement(name="AppAccountList")public class AppAccountListVO {private List<AppAccountEntity> appAccountList;public AppAccountListVO() {}public App...
·
使用jdk自带注解
在一个实体类上添加注解
@XmlRootElement(name="AppAccountList")
public class AppAccountListVO {
private List<AppAccountEntity> appAccountList;
public AppAccountListVO() {}
public AppAccountListVO(List<AppAccountEntity> appAccountList) {
this.appAccountList = appAccountList;
}
public List<AppAccountEntity> getAppAccountList() {
return appAccountList;
}
@XmlElement(name="AppAccount")
public void setAppAccountList(List<AppAccountEntity> appAccountList) {
this.appAccountList = appAccountList;
}
}
===========================================================
@XmlRootElement(name="AppAccount")
public class AppAccountEntity {
private String code;
private String appName;
private String appUrl;
private String redirectUrl;
private String userName;
private String passowrd;
private String state;
public String getCode() {
return code;
}
@XmlElement(name = "Code")
public void setCode(String Code) {
this.code = Code;
}
public String getAppName() {
return appName;
}
@XmlElement(name = "AppName")
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppUrl() {
return appUrl;
}
@XmlElement(name = "AppUrl")
public void setAppUrl(String appUrl) {
this.appUrl = appUrl;
}
public String getRedirectUrl() {
return redirectUrl;
}
@XmlElement(name = "RedirectUrl")
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public String getUserName() {
return userName;
}
@XmlElement(name = "UserName")
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassowrd() {
return passowrd;
}
@XmlElement(name = "Password")
public void setPassowrd(String passowrd) {
this.passowrd = passowrd;
}
public String getState() {
return state;
}
@XmlElement(name = "State")
public void setState(String state) {
this.state = state;
}
}
main方法测试
public class Main {
public static void main(String[] args) throws Exception{
List list = new ArrayList();
AppAccountEntity appAccountEntity = new AppAccountEntity();
appAccountEntity.setCode("code");
appAccountEntity.setAppName("appname");
list.add(appAccountEntity);
AppAccountListVO authVO = new AppAccountListVO(list);
JAXBContext context = JAXBContext.newInstance(AppAccountListVO.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//marshaller.marshal(authVO,System.out);
// 打印到控制台
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(authVO, baos);
String xmlObj = new String(baos.toByteArray());
// 生成XML字符串
System.out.println(xmlObj);
}
}
结果

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)