我在一个类中有一个属性“abc”。我想将此属性限制为转换为 XML 字符串格式。
是否有任何我可以在属性上使用的 XMl 注释,以避免将其转换为 XML 字符串?
请有人帮我解决这个问题。
最佳答案
可以使用@XmlTransient注解。
欲了解更多信息,请访问 @XmlTransient Sample
下面是在 JAXB 中避免 XML 转换中的“密码”属性的示例。因此它被注释为
@XmlTransient 注解
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlType(propOrder = { "phoneNumbers", "name"})
public class Customer extends Person {
private String password;
private List<String> phoneNumbers;
@XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlElement(name = "phone-number")
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
/* demo class*/
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
/*Generated xml doesn't have password tag */
/* <?xml version="1.0" encoding="UTF-8"?>
<customer>
<id>123</id>
<phone-number>555-1111</phone-number>
<phone-number>555-2222</phone-number>
<name>Jane Doe</name>
</customer>
*/
关于java - 可以阻止将属性转换为 xml 字符串的 xml 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17791543/