1. 程式人生 > 其它 >JAXB XML XSD JAVA Bean 之間的轉化

JAXB XML XSD JAVA Bean 之間的轉化

技術標籤:Javajaxbxmlxsd

目錄

將 XML 檔案(以.xml結尾)轉化為 Schema 檔案(以.xsd結尾)

將 Schema 轉換為 Java bean

XML和Java Bean之間的轉換

Testing


將 XML 檔案(以.xml結尾)轉化為 Schema 檔案(以.xsd結尾)

下載Trang.jar

java -jar trang.jar sample.xml sample.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ServiceRequest xmlns="http://com.csdn.uc">
    <ucAmount>100</ucAmount>
    <ucCurrency>CNY</ucCurrency>
</ServiceRequest>
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://com.csdn.uc" xmlns:ns1="http://com.csdn.uc">
  <xs:element name="ServiceRequest">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="ns1:ucAmount"/>
        <xs:element ref="ns1:ucCurrency"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="ucAmount" type="xs:integer"/>
  <xs:element name="ucCurrency" type="xs:NCName"/>
</xs:schema>

將 Schema 轉換為 Java bean

xjc -p com.csdn.uc sample.xsd
package com.csdn.uc;

import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;


/**
 * <p>Java class for anonymous complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element ref="{http://com.csdn.uc}ucAmount"/>
 *         &lt;element ref="{http://com.csdn.uc}ucCurrency"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "ucAmount",
    "ucCurrency"
})
@XmlRootElement(name = "ServiceRequest")
public class ServiceRequest {

    @XmlElement(required = true)
    protected BigInteger ucAmount;
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String ucCurrency;

    /**
     * Gets the value of the ucAmount property.
     * 
     * @return
     *     possible object is
     *     {@link BigInteger }
     *     
     */
    public BigInteger getUcAmount() {
        return ucAmount;
    }

    /**
     * Sets the value of the ucAmount property.
     * 
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *     
     */
    public void setUcAmount(BigInteger value) {
        this.ucAmount = value;
    }

    /**
     * Gets the value of the ucCurrency property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getUcCurrency() {
        return ucCurrency;
    }

    /**
     * Sets the value of the ucCurrency property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setUcCurrency(String value) {
        this.ucCurrency = value;
    }

}

XML和Java Bean之間的轉換

public class JAXBMessageConverter {

  private final static String DEFAULT_ENCODING = "UTF-8";

  /**
   * convert Message To Bean/Entity
   * @param message
   * @param objectClass
   * @return
   */
  public static <T> T fromMessage(String message, Class<T> objectClass) {
    T t = null;
    try {
      JAXBContext context = JAXBContext.newInstance(objectClass);
      Unmarshaller unmarshaller = context.createUnmarshaller();
      t = (T) unmarshaller.unmarshal(new StringReader(message));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return t;
  }

  public static <T> T fromMessageIgnoreNameSpace(String message, Class<T> objectClass) {
    T t = null;
    try {
      JAXBContext context = JAXBContext.newInstance(objectClass);
      Unmarshaller unmarshaller = context.createUnmarshaller();
      StringReader reader = new StringReader(message);
      SAXParserFactory sax = SAXParserFactory.newInstance();
      sax.setNamespaceAware(false);//Sets whether namespaces are ignored
      XMLReader xmlReader = sax.newSAXParser().getXMLReader();
      Source source = new SAXSource(xmlReader, new InputSource(reader));
      t = (T) unmarshaller.unmarshal(source);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return t;
  }

  /**
   * convert Bean/Entity to message
   * @param obj
   * @return
   */
  public static String toMessage(Object obj) {
    String result = null;
    try {
      JAXBContext context = JAXBContext.newInstance(obj.getClass());
      Marshaller marshaller = context.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_ENCODING);
      StringWriter writer = new StringWriter();
      marshaller.marshal(obj, writer);
      result = writer.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
}

Testing

public class ServiceRequestTest {

  @Test
  public void beanToXml(){
    ServiceRequest serviceRequest = new ServiceRequest();
    serviceRequest.setUcAmount(BigInteger.valueOf(100));
    serviceRequest.setUcCurrency("CNY");
    System.out.println(JAXBMessageConverter.toMessage(serviceRequest));
  }

  @Test
  public void xmlToBean(){
    String message = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
      "<ServiceRequest>\n" +
      "    <ucAmount>100</ucAmount>\n" +
      "    <ucCurrency>CNY</ucCurrency>\n" +
      "</ServiceRequest>";
    ServiceRequest serviceRequest = JAXBMessageConverter.fromMessage(message, ServiceRequest.class);
    Assert.assertEquals(BigInteger.valueOf(100), serviceRequest.getUcAmount());
    Assert.assertEquals("CNY", serviceRequest.getUcCurrency());
  }
}