如何动态地将对象与xml文件相互转换
如下面有一个用户类classUser{privateintyear;privateStringname;}我们实例化了一个用户对象newUser(1,"Lee"),现在要...
如下面有一个用户类
class User{
private int year;
private String name;
}
我们实例化了一个用户对象new User(1,"Lee"),现在要将其写入文件中,不是简单的序列化,而是节点的名字需要和属性一一对应,
若是直接将其序列化,是以下这种形式:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_13" class="java.beans.XMLDecoder">
<object class="User">
<void property="id">
<int>1</int>
</void>
<void property="name">
<string>Lee</string>
</void>
</object>
</java>
但我希望是存为以下这种形式:
<?xml version="1.0" encoding="UTF-8"?>
<User>
<year>1</year>
<name>Lee</name>
</User>
如何做到呢? 展开
class User{
private int year;
private String name;
}
我们实例化了一个用户对象new User(1,"Lee"),现在要将其写入文件中,不是简单的序列化,而是节点的名字需要和属性一一对应,
若是直接将其序列化,是以下这种形式:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_13" class="java.beans.XMLDecoder">
<object class="User">
<void property="id">
<int>1</int>
</void>
<void property="name">
<string>Lee</string>
</void>
</object>
</java>
但我希望是存为以下这种形式:
<?xml version="1.0" encoding="UTF-8"?>
<User>
<year>1</year>
<name>Lee</name>
</User>
如何做到呢? 展开
1个回答
展开全部
package org.Test.bean;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
int userId;
String userName;
String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int userId, String userName, String password) {
super();
this.userId = userId;
this.userName = userName;
this.password = password;
}
public User() {
}
}
public void beanToXML() {
User user=new User(1,"a","b");
try {
JAXBContext context = JAXBContext.newInstance(User.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(user, sw);
System.err.println(sw.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询