如何使用以下类中的 JAXB 单独获取 Xml 字符串中的一个属性:
例如:
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
XMLString 中的预期输出是:
<?xml version="1.0"?>
<student_list>
<id = “1234”/>
<id = “4567”/>
</student_list>
我需要与上面表示的格式相同的 xml 字符串。
最佳答案
选项#1 - @XmlTransient
您可以使用 @XmlTransient
映射您不希望出现在 XML 中的属性。
public class Student {
private Integer age;
private String name;
private Integer id;
@XmlTransient
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@XmlTrasient
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@XmlAttribute
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
选项 #2 - @XmlAccessorType(XmlAccessType.NONE)
或者,您可以使用 @XmlAccessorType(XmlAccessType.NONE)
注释您的类,以便仅带注释的属性包含在 XML 中。
@XmlAccessorType(XmlAccessType.NONE)
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@XmlAttribute
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
关于java - 从许多属性中,我需要获取其中之一并使用 jaxb 在 xml 字符串中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18593046/