2013-08-22 46 views
1

我想在javabean中存儲java字符串對象,並試圖將其轉換爲xml格式。它存儲成功,但每當我嘗試從java bean.i中獲取數據以簡單的字符串格式收到而不是xml格式。javabean到xmltype字符串

請幫幫我。

我的代碼是下面的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; 
} 
} 

回答

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),您還可以省略getters d安裝者:

@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; 
} 
+0

謝謝你的幫助。它的工作。 –