我正在尝试将java字符串对象存储在javabean中并尝试将其转换为xml格式。它存储成功,但每当我尝试从java bean.i获取数据时,以简单的字符串格式接收而不是xml格式。
请帮帮我。
我的代码如下所示:javabean:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "name", propOrder = {"username", "password"})
public class newBean {
@XmlElement(name = "username", required = true)
protected String username;
@XmlElement(name = "password", required = true)
protected String password;
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;
}
}
答案 0 :(得分:1)
如果在J2SE环境中需要来自bean的XML输出,可以试试这个:
StringWriter writer = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(newBean.class);
newBean bean = new newBean();
bean.setUsername("user");
bean.setPassword("secret");
JAXBElement<newBean> jaxbElement = new JAXBElement<Main.newBean>(new QName("name"), newBean.class, bean);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(jaxbElement, writer);
String result = writer.toString();
// print result to console
System.out.println(result);
但是使用@XmlRootElement anotation可能更容易:
StringWriter writer = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(newBean.class);
newBean bean = new newBean();
bean.setUsername("user");
bean.setPassword("secret");
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(bean, writer);
String result = writer.toString();
// print result to console
System.out.println(result);
请注意,使用@XmlAccessorType(XmlAccessType.FIELD),您还可以省略getter和setter:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "name", propOrder = { "username", "password" })
public static class newBean {
@XmlElement(name = "username", required = true)
protected String username;
@XmlElement(name = "password", required = true)
protected String password;
}