使用jaxb显示xml响应

问题描述:

我有一个responsewrapper类,它是一个泛型类,并以xml形式显示响应。使用jaxb显示xml响应

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement(name = "XML") 
public class ResponseWrapper<T> { 
private T Respsonse; 

ResponseWrapper(T Response){ 
    this.Respsonse=Response; 
} 

@XmlElement 
public T getRepsonse() { 
    return Respsonse; 
} 

public void setRepsonse(T repsonse) { 
    Respsonse = repsonse; 
} 

}

我有一个Employee类

public class Employee { 
public String name; 
public String address; 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getAddress() { 
    return address; 
} 

public void setAddress(String address) { 
    this.address = address; 
} 

}

测试类如下

public class Test { 
public static void main(String args[]) { 
    Employee e =new Employee(); 
    e.setName("guess"); 
    e.setAddress("xyz road and xyz country"); 
ResponseWrapper<Employee> resp=new ResponseWrapper<Employee>(e); 
Employee e1=(Employee)resp.getRepsonse(); 
System.out.print(resp); 

} 

}

当我运行测试类,我得到如下回应

ResponseWrapper此类@ 65690726 我预计在XML格式的响应:XML->员工 - >名称 - > /名称 - > ... /员工。任何人都可以请指导我哪里我错了。谢谢!

当试图转换的Employee到XML,下面是它是如何与JAXB完成:

员工

package forum9796799; 

import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class Employee { 

    private String name; 
    private String address; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

} 

测试

package forum9796799; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.Marshaller; 

public class Test { 
    public static void main(String args[]) throws Exception { 
     Employee e = new Employee(); 
     e.setName("guess"); 
     e.setAddress("xyz road and xyz country"); 

     JAXBContext jc = JAXBContext.newInstance(Employee.class); 
     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(e, System.out); 
    } 

} 

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<employee> 
    <address>xyz road and xyz country</address> 
    <name>guess</name> 
</employee> 
+0

嗨布莱斯谢谢你的回应。我知道如何marhsal对象到XML,但我怎么会为通用类ResponseWrapper它可以输出任何类型的对象。 – 2012-03-21 17:14:40

+0

@luckysing_noobster - 您是否在寻找类似以下内容的内容:http://blog.bdoughan.com/2010/08/using-xmlanyelement-to-build-generic.html – 2012-03-21 17:18:08

+0

谢谢,我会看看它。我想在ResponseWrapper xml.So内嵌入Employee xml如果我需要添加任何类型的响应类型,我可以简单地将它附加到ResponseWrapper。 – 2012-03-21 17:30:58