JAXB:使用annotation绑定XML(xmlns)

在java开发中使用XML几乎是每个程序员都会碰到的,目前可供我们选择的库也有很多,包括,dom4j, jaxen,  SAX等等,本文将介绍如何使用JAXB进行Object-XML mapping.



JAXB目前已经集成到了JDK6中,但是还是推荐下载使用最新版的jaxb库, https://jaxb.dev.java.net/



从JAXB2.0开始,可以通过使用annotation进行Object-XMl mapping。



本文将通过以下步骤演示如何使用JAXB annotation绑定使用了namespace的XML文件

1. 创建employees.xml文件

2. 创建Employees.java和Employee.java绑定employees.xml

3. 创建package-info.java和jaxb.index文件

4. 创建XMLParser.java封装marshal/unmarshal操作

5. 创建Test.java运行测试



现在将逐步展开演示

1. 创建employees.xml文件

现在将逐步展开演示

1. 创建employees.xml文件

Xml代码 
1.<?xml version="1.0" encoding="utf-8" ?> 
2.<employees xmlns:admin="http://www.company.com/management/employees/admin"> 
3.    <admin:employee> 
4.        <admin:userId>[email protected]</admin:userId> 
5.        <admin:password>abc123_</admin:password> 
6.        <admin:name>John Smith</admin:name> 
7.        <admin:age>24</admin:age> 
8.        <admin:gender>Male</admin:gender> 
9.    </admin:employee> 
10.    <admin:employee> 
11.        <admin:userId>[email protected]</admin:userId> 
12.        <admin:password>123456</admin:password> 
13.        <admin:name>Christine Chen</admin:name> 
14.        <admin:age>27</admin:age> 
15.        <admin:gender>Female</admin:gender> 
16.    </admin:employee> 
17.</employees> 
<?xml version="1.0" encoding="utf-8" ?>
<employees xmlns:admin="http://www.company.com/management/employees/admin">
<admin:employee>
<admin:userId>[email protected]</admin:userId>
<admin:password>abc123_</admin:password>
<admin:name>John Smith</admin:name>
<admin:age>24</admin:age>
<admin:gender>Male</admin:gender>
</admin:employee>
<admin:employee>
<admin:userId>[email protected]</admin:userId>
<admin:password>123456</admin:password>
<admin:name>Christine Chen</admin:name>
<admin:age>27</admin:age>
<admin:gender>Female</admin:gender>
</admin:employee>
</employees> 这是一个很普通的xml文件,用于展示组织内部的成员(employee)状况,这里有一点需要注意的是使用了namespace,这也是本文将要演示的重点。



2.
 创建Employees.java和Employee.java绑定employees.xml

 

Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.import java.util.ArrayList;   
4.import java.util.List;   
5.  
6.import javax.xml.bind.annotation.XmlElement;   
7.import javax.xml.bind.annotation.XmlRootElement;   
8.  
9.@XmlRootElement(name = "employees")   
10.public class Employees {   
11.  
12.    @XmlElement(name = "employee", namespace=NameSpace.ADMIN_URI)   
13.    private List<Employee> employees;   
14.  
15.    public Employees() {   
16.        employees = new ArrayList<Employee>();   
17.    }   
18.  
19.    public List<Employee> getEmployees() {   
20.        return employees;   
21.    }   
22.       
23.    public void addEmployee(Employee employee) {   
24.        employees.add(employee);   
25.    }   
26.  
27.}  
package com.javaeye.terrencexu.jaxb;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employees")
public class Employees {

	@XmlElement(name = "employee", namespace=NameSpace.ADMIN_URI)
	private List<Employee> employees;

	public Employees() {
		employees = new ArrayList<Employee>();
	}

	public List<Employee> getEmployees() {
		return employees;
	}
	
	public void addEmployee(Employee employee) {
		employees.add(employee);
	}

} 

 

Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.import javax.xml.bind.annotation.XmlElement;   
4.  
5.public class Employee {   
6.  
7.    @XmlElement(name = "userId", namespace=NameSpace.ADMIN_URI)   
8.    private String userId;   
9.  
10.    @XmlElement(name = "password", namespace=NameSpace.ADMIN_URI)   
11.    private String password;   
12.  
13.    @XmlElement(name = "name", namespace=NameSpace.ADMIN_URI)   
14.    private String name;   
15.  
16.    @XmlElement(name = "age", namespace=NameSpace.ADMIN_URI)   
17.    private int age;   
18.  
19.    @XmlElement(name = "gender", namespace=NameSpace.ADMIN_URI)   
20.    private String gender;   
21.  
22.    public Employee() {   
23.    }   
24.  
25.    public Employee(String userId, String psw, String name, int age, Gender gender) {   
26.        this.userId = userId;   
27.        this.password = psw;   
28.        this.name = name;   
29.        this.age = age;   
30.        this.gender = gender.getValue();   
31.    }   
32.  
33.    public String getUserId() {   
34.        return userId;   
35.    }   
36.  
37.    public String getPassword() {   
38.        return password;   
39.    }   
40.  
41.    public String getName() {   
42.        return name;   
43.    }   
44.  
45.    public int getAge() {   
46.        return age;   
47.    }   
48.  
49.    public String getGender() {   
50.        return gender;   
51.    }   
52.  
53.}  
package com.javaeye.terrencexu.jaxb;

import javax.xml.bind.annotation.XmlElement;

public class Employee {

	@XmlElement(name = "userId", namespace=NameSpace.ADMIN_URI)
	private String userId;

	@XmlElement(name = "password", namespace=NameSpace.ADMIN_URI)
	private String password;

	@XmlElement(name = "name", namespace=NameSpace.ADMIN_URI)
	private String name;

	@XmlElement(name = "age", namespace=NameSpace.ADMIN_URI)
	private int age;

	@XmlElement(name = "gender", namespace=NameSpace.ADMIN_URI)
	private String gender;

	public Employee() {
	}

	public Employee(String userId, String psw, String name, int age, Gender gender) {
		this.userId = userId;
		this.password = psw;
		this.name = name;
		this.age = age;
		this.gender = gender.getValue();
	}

	public String getUserId() {
		return userId;
	}

	public String getPassword() {
		return password;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public String getGender() {
		return gender;
	}

}
 

 

Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.public class NameSpace {   
4.  
5.    public static final String ADMIN_PREFIX = "admin";   
6.    public static final String ADMIN_URI = "http://www.company.com/management/employees/admin";   
7.  
8.}  
package com.javaeye.terrencexu.jaxb;

public class NameSpace {

	public static final String ADMIN_PREFIX = "admin";
	public static final String ADMIN_URI = "http://www.company.com/management/employees/admin";

} 

Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.public enum Gender {   
4.  
5.    MALE("Male"),   
6.    FEMALE("Female");   
7.       
8.    private String value;   
9.       
10.    private Gender(String value) {   
11.        this.value = value;   
12.    }   
13.       
14.    public String getValue() {   
15.        return this.value;   
16.    }   
17.       
18.}  
package com.javaeye.terrencexu.jaxb;

public enum Gender {

	MALE("Male"),
	FEMALE("Female");
	
	private String value;
	
	private Gender(String value) {
		this.value = value;
	}
	
	public String getValue() {
		return this.value;
	}
	
} 

3. 创建package-info.java和jaxb.index文件

创建package-info.java注册xmlns, 将该文件放在当前source code的package下面,如果不使用namespace可以不创建该文件

Java代码  
1.@XmlSchema(   
2.xmlns={   
3.        @XmlNs(prefix=NameSpace.ADMIN_PREFIX, namespaceURI=NameSpace.ADMIN_URI)   
4.}   
5.)   
6.package com.javaeye.terrencexu.jaxb;   
7.import javax.xml.bind.annotation.XmlNs;   
8.import javax.xml.bind.annotation.XmlSchema;  
@XmlSchema(
xmlns={
		@XmlNs(prefix=NameSpace.ADMIN_PREFIX, namespaceURI=NameSpace.ADMIN_URI)
}
)
package com.javaeye.terrencexu.jaxb;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema; 

创建jaxb.index注册Employees, Employee,如果不使用包级context,可以不创建该文件

Java代码  
1.Employees   
2.Employee  
Employees
Employee 

 

4. 创建XMLParser.java封装marshal/unmarshal操作

 

Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.import java.io.InputStream;   
4.import java.io.StringWriter;   
5.  
6.import javax.xml.bind.JAXBContext;   
7.import javax.xml.bind.JAXBException;   
8.import javax.xml.bind.Marshaller;   
9.import javax.xml.bind.Unmarshaller;   
10.  
11.public final class XMLParser {   
12.  
13.    private XMLParser() {}   
14.       
15.    public static Object unmarshal(InputStream xml, Class<?> clazz) {   
16.        Object obj = null;   
17.           
18.        try {   
19.            JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());   
20.            Unmarshaller u = jc.createUnmarshaller();   
21.            obj = u.unmarshal(xml);   
22.        } catch (JAXBException e) {   
23.            throw new RuntimeException("Can't unmarshal the XML file, error message: " + e.getMessage());   
24.        }   
25.           
26.        return obj;   
27.    }   
28.       
29.    public static String marshal(Object obj, Class<?> clazz) {   
30.        String result = null;   
31.           
32.        try {   
33.            JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());   
34.            Marshaller m = jc.createMarshaller();   
35.               
36.            StringWriter writer = new StringWriter();   
37.               
38.            m.marshal(obj, writer);   
39.               
40.            result = writer.toString();   
41.        } catch (JAXBException e) {   
42.            throw new RuntimeException("Can't marshal the XML file, error message: " + e.getMessage());   
43.        }   
44.           
45.           
46.        return result;   
47.    }   
48.       
49.}  
package com.javaeye.terrencexu.jaxb;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public final class XMLParser {

	private XMLParser() {}
	
	public static Object unmarshal(InputStream xml, Class<?> clazz) {
		Object obj = null;
		
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());
			Unmarshaller u = jc.createUnmarshaller();
			obj = u.unmarshal(xml);
		} catch (JAXBException e) {
			throw new RuntimeException("Can't unmarshal the XML file, error message: " + e.getMessage());
		}
		
		return obj;
	}
	
	public static String marshal(Object obj, Class<?> clazz) {
		String result = null;
		
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());
			Marshaller m = jc.createMarshaller();
			
			StringWriter writer = new StringWriter();
			
			m.marshal(obj, writer);
			
			result = writer.toString();
		} catch (JAXBException e) {
			throw new RuntimeException("Can't marshal the XML file, error message: " + e.getMessage());
		}
		
		
		return result;
	}
	
}




5. 创建Test.java运行测试



Java代码  
1.package com.javaeye.terrencexu.jaxb;   
2.  
3.import java.io.File;   
4.import java.io.FileInputStream;   
5.import java.io.FileNotFoundException;   
6.import java.util.List;   
7.  
8.public class Test {   
9.  
10.    public static void main(String[] args) throws FileNotFoundException {   
11.        testUnmarshal();   
12.        testMarshal();   
13.    }   
14.  
15.    public static void testUnmarshal() throws FileNotFoundException {   
16.        Employees employees = (Employees) XMLParser.unmarshal(   
17.          new FileInputStream(new File("F:\\workspace\\JavaStudy\\test\\employees.xml")),   
18.          Employees.class);   
19.  
20.        List<Employee> employeeList = employees.getEmployees();   
21.  
22.        if (employeeList != null && employeeList.size() > 0) {   
23.            for (Employee employee : employeeList) {   
24.                StringBuilder builder = new StringBuilder();   
25.                builder.append("[UserID: ").append(employee.getUserId()).append(", ")   
26.                       .append("Password: ").append(employee.getPassword()).append(", ")   
27.                       .append("Name: ").append(employee.getName()).append(", ")   
28.                       .append("Age: ").append(employee.getAge()).append(", ")   
29.                       .append("Gender").append(employee.getGender()).append("]");   
30.  
31.                System.out.println(builder.toString());   
32.            }   
33.        }   
34.    }   
35.       
36.    public static void testMarshal() {   
37.        Employees employees = new Employees();   
38.        employees.addEmployee(new Employee("[email protected]", "abc123_", "John Smith", 24, Gender.MALE));   
39.        employees.addEmployee(new Employee("[email protected]", "123456", "Christine Chen", 27, Gender.FEMALE));   
40.           
41.        String result = XMLParser.marshal(employees, Employees.class);   
42.        System.out.println(result);   
43.    }   
44.}  
package com.javaeye.terrencexu.jaxb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

public class Test {

	public static void main(String[] args) throws FileNotFoundException {
		testUnmarshal();
		testMarshal();
	}

	public static void testUnmarshal() throws FileNotFoundException {
		Employees employees = (Employees) XMLParser.unmarshal(
		  new FileInputStream(new File("F:\\workspace\\JavaStudy\\test\\employees.xml")),
		  Employees.class);

		List<Employee> employeeList = employees.getEmployees();

		if (employeeList != null && employeeList.size() > 0) {
			for (Employee employee : employeeList) {
				StringBuilder builder = new StringBuilder();
				builder.append("[UserID: ").append(employee.getUserId()).append(", ")
				       .append("Password: ").append(employee.getPassword()).append(", ")
				       .append("Name: ").append(employee.getName()).append(", ")
				       .append("Age: ").append(employee.getAge()).append(", ")
				       .append("Gender").append(employee.getGender()).append("]");

				System.out.println(builder.toString());
			}
		}
	}
	
	public static void testMarshal() {
		Employees employees = new Employees();
		employees.addEmployee(new Employee("[email protected]", "abc123_", "John Smith", 24, Gender.MALE));
		employees.addEmployee(new Employee("[email protected]", "123456", "Christine Chen", 27, Gender.FEMALE));
		
		String result = XMLParser.marshal(employees, Employees.class);
		System.out.println(result);
	}
}


6. 运行结果:

Java代码  
1.[UserID: [email protected], Password: abc123_, Name: John Smith, Age: 24, GenderMale]   
2.[UserID: [email protected], Password: 123456, Name: Christine Chen, Age: 27, GenderFemale]   
3.<?xml version="1.0" encoding="UTF-8" standalone="yes"?><employees xmlns:admin="http://www.company.com/management/employees/admin"><admin:employee><admin:userId>[email protected]</admin:userId><admin:password>abc123_</admin:password><admin:name>John Smith</admin:name><admin:age>24</admin:age><admin:gender>Male</admin:gender></admin:employee><admin:employee><admin:userId>[email protected]</admin:userId><admin:password>123456</admin:password><admin:name>Christine Chen</admin:name><admin:age>27</admin:age><admin:gender>Female</admin:gender></admin:employee></employees> 

你可能感兴趣的:(xml)