天天看點

JAX-RS XML

JAX-RS(Java API for RESTful Web Services)

javax.xml.transform.Source Example:

The javax.xml.transform.Source interface represents XML input or output.It is usually used to perform XSLT(Extensible Stylesheet Language Transform) transformations on input documents.
@Path("/transform")
public class TransformationService {

  @POST
  @Consumes("application/xml")
  @Produces("application/xml")
  public String post(Source source) {

    javax.xml.transform.TransformerFactory tFactory =
      javax.xml.transform.TransformerFactory.newInstance();
    javax.xml.transform.Transformer transformer =
    tFactory.newTransformer(
      new javax.xml.transform.stream.StreamSource("foo.xsl"));
    StringWriter writer = new StringWriter();
    transformer.transform(source, 
      new javax.xml.transform.stream.StreamResult(writer));
    return writer.toString();

  }
           

JAXB(Java Architecture for XML Binding) Example:

@XmlRootElement(name="customer")
  @XmlAccessorType(XmlAccessType.FIELD)
  public class Customer {

    @XmlAttribute
    protected int id;
    @XmlElement
    protected String name;
    @XmlElement
    protected Address address;

    public Customer() {}
    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }
    ...

  }

  ---------

  Customer customer = new Customer();
  customer.setId();
  customer.setName("Bill Burke");
  JAXBContext ctx = JAXBContext.newInstance(Customer.class);
  StringWriter writer = new StringWriter();
  ctx.createMarshaller().marshal(customer, writer);
  String custString = writer.toString();
  customer = (Customer)ctx.createUnmarshaller().unmarshal(
    new StringReader(custString));