JAXB XML XSD JAVA Bean 之间的转化

目录

将 XML 文件(以.xml结尾)转化为 Schema 文件(以.xsd结尾)

将 Schema 转换为 Java bean

XML和Java Bean之间的转换

Testing


将 XML 文件(以.xml结尾)转化为 Schema 文件(以.xsd结尾)

下载 Trang.jar

1
java -jar trang.jar sample.xml sample.xsd
1
2
3
4
5
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ServiceRequest xmlns="http://com.csdn.uc">
    <ucAmount>100</ucAmount>
    <ucCurrency>CNY</ucCurrency>
</ServiceRequest>
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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

1
xjc -p com.csdn.uc sample.xsd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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>
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://com.csdn.uc}ucAmount"/>
 *         <element ref="{http://com.csdn.uc}ucCurrency"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </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之间的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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());
  }
}