Background Information (from Related Question )
From the comment you made in response to your previous question, the domain model is already in use with JAXB. The easiest way to communicate with your client and server via XML is to use an already annotated model at both ends.
. XML , java- xml : javax.xml.bind.JAXBContext javax.xml.bind.Marshaller. , xml java-? java- . !
UPDATE
, , . , , JAXB (Metro, MOXy, JaxMe ..).
-
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(CustomerImpl.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
Address address = customer.getAddress();
System.out.println(address.getStreet());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
. JAXBContext.
public interface Customer {
public Address getAddress();
public void setAddress(Address address);
}
public interface Address {
public String getStreet();
public void setStreet(String street);
}
- , XML JAXB.
CustomerImpl
, CustomerImpl @XmlElement address AddressImpl.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="customer")
public class CustomerImpl implements Customer {
private Address address;
@XmlElement(type=AddressImpl.class)
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
AddressImpl
public class AddressImpl implements Address {
private String street;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
Input.xml
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<address>
<street>1 Any Street</street>
</address>
</customer>