01 | package com.mkyong.core; |
02 | |
03 | import javax.xml.bind.annotation.XmlAttribute; |
04 | import javax.xml.bind.annotation.XmlElement; |
05 | import javax.xml.bind.annotation.XmlRootElement; |
06 | |
07 | @XmlRootElement |
08 | public class
Customer { |
09 | |
10 | String name; |
11 | int
age; |
12 | int
id; |
13 | |
14 | public
String getName() { |
15 | return
name; |
16 | } |
17 | |
18 | @XmlElement |
19 | public
void setName(String name) { |
20 | this .name = name; |
21 | } |
22 | |
23 | public
int getAge() { |
24 | return
age; |
25 | } |
26 | |
27 | @XmlElement |
28 | public
void setAge( int
age) { |
29 | this .age = age; |
30 | } |
31 | |
32 | public
int getId() { |
33 | return
id; |
34 | } |
35 | |
36 | @XmlAttribute |
37 | public
void setId( int
id) { |
38 | this .id = id; |
39 | } |
40 | |
41 | } |
[代码] JAXBExample.java
01 | package com.mkyong.core; |
02 | |
03 | import java.io.File; |
04 | import javax.xml.bind.JAXBContext; |
05 | import javax.xml.bind.JAXBException; |
06 | import javax.xml.bind.Marshaller; |
07 | |
08 | public class
JAXBExample { |
09 | public
static void
main(String[] args) { |
10 | |
11 | Customer customer =
new Customer(); |
12 | customer.setId( 100 ); |
13 | customer.setName( "mkyong" ); |
14 | customer.setAge( 29 ); |
15 | |
16 | try
{ |
17 | |
18 | File file =
new File( "C:\\file.xml" ); |
19 | JAXBContext jaxbContext = JAXBContext.newInstance(Customer. class ); |
20 | Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); |
21 | |
22 | // output pretty printed |
23 | jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
true ); |
24 | |
25 | jaxbMarshaller.marshal(customer, file); |
26 | jaxbMarshaller.marshal(customer, System.out); |
27 | |
28 | }
catch (JAXBException e) { |
29 | e.printStackTrace(); |
30 | } |
31 | |
32 | } |
33 | } |
[代码] 输出
1 | <? xml
version = "1.0"
encoding = "UTF-8"
standalone = "yes" ?> |
2 | < customer
id = "100" > |
3 | < age >29</ age > |
4 | < name >mkyong</ name > |
5 | </ customer > |
[代码] 将XML转为对象
01 | package com.mkyong.core; |
02 | |
03 | import java.io.File; |
04 | import javax.xml.bind.JAXBContext; |
05 | import javax.xml.bind.JAXBException; |
06 | import javax.xml.bind.Unmarshaller; |
07 | |
08 | public class
JAXBExample { |
09 | public
static void
main(String[] args) { |
10 | |
11 | try
{ |
12 | |
13 | File file =
new File( "C:\\file.xml" ); |
14 | JAXBContext jaxbContext = JAXBContext.newInstance(Customer. class ); |
15 | |
16 | Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); |
17 | Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); |
18 | System.out.println(customer); |
19 | |
20 | }
catch (JAXBException e) { |
21 | e.printStackTrace(); |
22 | } |
23 | |
24 | } |
25 | } |
[代码] 输出
1 | Customer [name=mkyong, age= 29 , id= 100 ] |