Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?

for example:

public class Customer {

    private String name;
    private int age;
    private int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

and let the unmarshalling code for properly annotated class be like:

try {

        File file = new File("C:\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
        System.out.println(customer);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

leaving out the details.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
548 views
Welcome To Ask or Share your Answers For Others

1 Answer

Following code is used to marshall and unmarshall withot @XmlRootElement

public static void main(String[] args) {

        try {

            StringWriter stringWriter = new StringWriter();

            Customer c = new Customer();
            c.setAge(1);
            c.setName("name");

            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.marshal(new JAXBElement<Customer>( new QName("", "Customer"), Customer.class, null, c), stringWriter);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
            JAXBElement<Customer> customer = (JAXBElement<Customer>) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class);

            c = customer.getValue();

          } catch (JAXBException e) {
            e.printStackTrace();
          }

}

Above code works only if you adding @XmlAccessorType(XmlAccessType.PROPERTY) on Customer class, or make private all attributes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...