这是我的班级
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Martin Burchard
*
*/
@XmlRootElement(name = "user")
public class User {
private String id;
private String nickname;
private String email;
private String password;
@XmlElement(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "nickname")
public String getNickName() {
return nickname;
}
public void setNickName(String nickname) {
this.nickname = nickname;
}
@XmlElement(name = "email")
public String getEMail() {
return email;
}
public void setEMail(String email) {
this.email = email;
}
@XmlElement(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在创建/注册用户期间,必须提供密码,但稍后,在要求用户信息时,XML不应包含密码元素.
是否可以将Element定义为writeonly?
解决方法:
注意:我是EclipseLink JAXB (MOXy)领导者,也是JAXB 2 (JSR-222)专家组的成员.
MOXy有一个@XmlReadOnly扩展名.使用@XmlReadOnly注释的字段/属性将在unmarshal(读取)期间填充,但在编组期间不会写入.
用户
package forum10208143;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlReadOnly;
/**
* @author Martin Burchard
*
*/
@XmlRootElement(name = "user")
public class User {
private String id;
private String nickname;
private String email;
private String password;
@XmlElement(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "nickname")
public String getNickName() {
return nickname;
}
public void setNickName(String nickname) {
this.nickname = nickname;
}
@XmlElement(name = "email")
public String getEMail() {
return email;
}
public void setEMail(String email) {
this.email = email;
}
@XmlElement(name = "password")
@XmlReadOnly
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
jaxb.properites
要将MOXy指定为JAXB提供程序,您需要在与域模型相同的包中添加名为jaxb.properties的文件,并使用以下条目:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
演示
package forum10208143;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(User.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10208143/input.xml");
User user = (User) unmarshaller.unmarshal(xml);
System.out.println(user.getPassword());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(user, System.out);
}
}
input.xml中
<?xml version="1.0" encoding="UTF-8"?>
<user>
<id>jdoe</id>
<nickname>Jane</nickname>
<email>jane.doe@example.com</email>
<password>secret</password>
</user>
产量
secret
<?xml version="1.0" encoding="UTF-8"?>
<user>
<email>jane.doe@example.com</email>
<id>jdoe</id>
<nickname>Jane</nickname>
</user>