отображать xml-ответ, используя jaxb - PullRequest
1 голос
/ 21 марта 2012

У меня есть класс responsewrapper, который является универсальным классом и отображает ответ в виде 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-> name -> / name -> ... / employee. Может кто-нибудь подсказать мне, где я ошибаюсь. Спасибо!

1 Ответ

0 голосов
/ 21 марта 2012

При попытке преобразовать Employee в XML, вот как это делается с JAXB:

Employee

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;
    }

}

Test

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...