1

我正在尝试将 java 字符串对象存储在 javabean 中并尝试将其转换为 xml 格式。它已成功存储,但每当我尝试从 java bean 获取数据时。我以简单的字符串格式而不是 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;
}
}
4

1 回答 1

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 注释可能更容易:

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;
}
于 2013-08-22T15:33:43.267 回答