`

Xml与Java Object 的转换[JAXB]

 
阅读更多
package ycl.learn.xml.jaxb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

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

public class JAXBUtil<T> {

	@SuppressWarnings("unchecked")
	public T unmarshal(Class<T> clazz, InputStream is) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller un = context.createUnmarshaller();
		return (T) un.unmarshal(is);
	}
	
	public T unmarshal(Class<T> clazz, File file) throws JAXBException, FileNotFoundException {
		return unmarshal(clazz,new FileInputStream(file));
	}
	
	public void marshal(T element,OutputStream os) throws JAXBException{
		JAXBContext jc = JAXBContext.newInstance(element.getClass());
		Marshaller m = jc.createMarshaller();
		m.marshal(element, os);
	}
	
	public void marshal(T element, File output) throws FileNotFoundException, JAXBException{
		marshal(element,new FileOutputStream(output));
	}
	
 
}



this is the simple util that packaging the JAXB operator.
then we can use it simplely.

1. we just export simple JODO to xml
package ycl.learn.xml.jaxb;

import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement 
public class EmployeeDO {
	private int id;

	private String gender;

	private int age;

	private String name;

	private String role;

	private String password;
 
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
 
	public int getId() {
		return id;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
 
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}
}


we must add @XmlRootElement to point this object is the root object for export.
package ycl.learn.xml.jaxb;

import java.io.File;
import java.io.FileNotFoundException;

import javax.xml.bind.JAXBException;

public class JAXBUtilTest {
	private static final String FILE_NAME = "jaxb-emp-jaxbutil.xml";
	/**
	 * @param args
	 * @throws JAXBException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException, JAXBException {
		// TODO Auto-generated method stub
		EmployeeDO emp = new EmployeeDO();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");
		JAXBUtil<EmployeeDO> ju = new JAXBUtil<EmployeeDO>();
		ju.marshal(emp, new File(FILE_NAME));
		System.out.println("generator success");
		EmployeeDO empant = ju.unmarshal(EmployeeDO.class, new File(FILE_NAME));
		System.out.println("reader success");
		System.out.println(empant);
	}

}



we can easily use JAXBUtil to marshal Object to file.
we can also easily use JAXBUtil to unmarchal File to Object.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employeeDO>
	<age>25</age>
	<gender>Male</gender>
	<id>1</id>
	<name>Pankaj</name>
	<password>sensitive</password>
	<role>Developer</role>
</employeeDO>


If you review this code carefully, you will find the default root element name is the Object's name with first letter is lowercase.
the element under the root element is the attribute of the object.
Q1: can i change the Element Name, to generator Xml
package ycl.learn.xml.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name="content") 
public class EmployeeDO {
	private int id;

	private String gender;

	private int age;

	private String name;

	private String role;

	private String password;
 
	@XmlElement(name="pwd")
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
 
	public int getId() {
		return id;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
 
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}
}

we just need to set the @XmlRootElement or @XmlElement's name is ok.then the xml content is
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<content>
	<age>25</age>
	<gender>Male</gender>
	<id>1</id>
	<name>Pankaj</name>
	<pwd>sensitive</pwd>
	<role>Developer</role>
</content>


Q2: can i point that some attribute of Object i don't want to export

package ycl.learn.xml.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
 
@XmlRootElement(name="content") 
public class EmployeeDO {
	private int id;

	private String gender;

	private int age;

	private String name;

	private String role;

	private String password;
 
	@XmlElement(name="pwd")
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
 
	@XmlTransient
	public int getId() {
		return id;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
 
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}
}


you can add @XmlTransient before the getMethod, then this attribute won't be export.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<content>
	<age>25</age>
	<gender>Male</gender>
	<name>Pankaj</name>
	<pwd>sensitive</pwd>
	<role>Developer</role>
</content>


Q3: can i export the attribute of Object as attribute, not Element of xml, and change the attribute name

@XmlAttribute(name="agefather")
	public int getAge() {
		return age;
	}

very easily to change sub element to attribute.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<content agefather="25">
	<gender>Male</gender>
	<name>Pankaj</name>
	<pwd>sensitive</pwd>
	<role>Developer</role>
</content>


Q4: i want to export the xml element as my order

@XmlRootElement(name="content") 
@XmlType(propOrder={"gender","age","name","role","password"})
public class EmployeeDO 


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<content agefather="25">
	<gender>Male</gender>
	<name>Pankaj</name>
	<role>Developer</role>
	<pwd>sensitive</pwd>
</content>


you can see this element is ordered by our defined.

Q5: i want to export list of Objects

         @XmlElementWrapper(name="employees")
	@XmlElement(name="employee")
	public List<Employee> getEmployees() {
		return employees;
	}


<employees>
    	<employee>
		    <age>25</age>
		    <gender>GGGGGG</gender>
		    <id>1</id>
		    <name>Pankaj</name>
		    <password>sensitive</password>
		    <role>Developer</role> 
		    <family></family>
		</employee>
		<employee>
		    <age>25</age>
		    <gender>GGGGGGG</gender>
		    <id>1</id>
		    <name>Pankaj</name>
		    <password>sensitive</password>
		    <role>Developer</role> 
		    <family></family>
		</employee>
    </employees>


Q5: i want to export list of Objects in other Object

[ClassA]
public Family getFamily() {
		return family;
	}


public class Family {

	private List<Employee> employees;
	
	@XmlElement(name="employee")
	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	} 
}

<family>
     	<employee>
		    <age>25</age>
		    <gender>LLLLLLL</gender>
		    <id>1</id>
		    <name>Pankaj</name>
		    <password>sensitive</password>
		    <role>Developer</role> 
		    <family></family>
		</employee>
		<employee>
		    <age>25</age>
		    <gender>Male</gender>
		    <id>1</id>
		    <name>Pankaj</name>
		    <password>sensitive</password>
		    <role>Developer</role> 
		    <family></family>
		</employee>
    </family>


oh, you just don't to defined family, because it is the element of the object, default define is ok.
the employee is multiple in family, you just define the @XmlElement empoyee is ok,and this will be auto add to list

so this is you can think of the four questions, and i can't think other situations, and i think this four points can resolve all problems that we encountered, we can easily change xml Element name, Element attribute, Element order, that's cool.
分享到:
评论

相关推荐

    JAXB工具类 xml转为java对象 java对象转为xml

    Java Architecture for XML Binding (JAXB) 是Java平台中用于处理XML和Java对象之间转换的一个标准API。它使得在Java应用程序中使用...在实际项目中,结合JAXB与XML Schema,可以构建更健壮、易于维护的数据交换系统。

    webservice之使用jaxb把xml转换Object或把对象转换成xml文件

    JAXB与其他XML处理技术(如DOM、SAX、StAX)相比,更注重于对象模型与XML之间的绑定,适用于需要频繁进行对象与XML转换的场景。而DOM适合处理小规模的XML文档,SAX和StAX则适用于大文件流式处理。 总结,JAXB是Java...

    JAVA JAXB 解析XML嵌套子节点为字符串

    在Java开发中,JAXB(Java Architecture for XML Binding)是一个标准的API,用于将XML文档与Java对象之间进行互相转换。这个技术对于处理XML数据,尤其是解析和生成XML文档非常有用。当我们面临XML文档中存在嵌套子...

    Object-XML文件的相互转换分析

    这个过程通常通过特定的API或库来实现,如JAXB(Java Architecture for XML Binding)或DOM(Document Object Model)。这些工具能够自动将Java对象的属性映射到XML元素和属性上,反之亦然。 Spring框架提供了一种...

    java 使用 JAXB 将xml转换为 bean 包含xml和dto和读取文件的util类

    总结来说,这个压缩包提供的内容涉及了Java中使用JAXB进行XML与Java对象之间转换的实际应用,以及辅助的DTO和文件读取工具。这些对于理解和实现XML数据处理的Java应用非常有帮助。开发者可以通过学习和使用这些示例...

    XML动态转化为ObjectDemo

    在“XML动态转化为ObjectDemo”中,JAXB可能是实现XML到Object转换的主要工具。 3. **XML到Object转换步骤**: - 定义Java类:根据XML结构创建相应的Java类,每个元素对应类的一个字段,属性对应字段的注解。 - ...

    Object转xml或xml转Object

    在编程领域,Object与XML之间的转换是常见的数据处理任务,特别是在数据交换、持久化存储或者网络通信中。Object转XML和XML转Object的过程涉及到对象序列化和反序列化的概念。 对象序列化是将一个对象的状态转化...

    利用jaxb实现xml和bean互转

    JAXB可以基于XML Schema自动生成Java Bean类,或者将Java Bean类转换为XML Schema。 3. **Marshalling**: 将Java对象转换为XML的过程称为 marshalling。JAXB提供了`Marshaller`接口来实现这一功能。 4. **...

    jaxb (XML操作)

    **JAXB(Java Architecture for XML Binding)** 是Java平台中用于处理XML的一种强大的工具,它提供了将XML文档与Java对象之间的映射,从而方便XML数据的解析和生成。通过JAXB,开发者可以轻松地实现XML数据到Java...

    xml和java对象互相转换的两种方法

    本文将详细介绍两种主要的XML与Java对象互相转换的方法:DOM(Document Object Model)解析和JAXB(Java Architecture for XML Binding)。 1. DOM解析: DOM是一种W3C标准,它将XML文档解析成一棵由节点组成的树,...

    XML、JAVA、JSON多种方式互相转换

    下面我们将详细探讨XML、Java与JSON的转换方法。 1. XML到JSON转换: - 使用Java的Jackson库:Jackson库中的`com.fasterxml.jackson.databind.ObjectMapper`类提供了将XML转换为JSON的功能。首先,我们需要解析XML...

    xml与java对象映射

    通过在Java类上使用特定的注解,JAXB可以将Java对象转换为XML文档,反之亦然。 - **DOM(Document Object Model)**:DOM是一种将XML文档解析成树形结构的API,每个节点代表XML文档的一部分。Java程序员可以通过...

    java对象转换成xml格式

    JAXB是Java SE的一部分,它提供了将Java对象直接转换为XML文档,以及从XML文档反序列化回Java对象的能力。首先,你需要为要转换的对象创建对应的Java类,并使用`@XmlRootElement`、`@XmlElement`等注解来指定XML...

    java list和xml互转例子

    本示例涉及的核心知识点是将Java中的List对象与XML文档进行相互转换。这里,我们使用的库是dom4j-1.6.1.jar,这是一个强大的Java XML处理库。 首先,让我们详细了解一下List和XML。List是Java集合框架的一部分,它...

    JAXB 生成XML文件

    5. **绑定上下文(Binder)**:`Binder`接口提供了在Java对象和XML DOM(Document Object Model)之间转换的能力,允许在处理XML时进行更灵活的操作。 6. **JAXB API**:`jaxb-api-2.2.6.jar`是JAXB的API库,其中...

    基于java的转换xml.zip

    在Java中处理XML,我们可以使用多种库和API,如JAXB (Java Architecture for XML Binding),DOM (Document Object Model),SAX (Simple API for XML) 和StAX (Streaming API for XML)。但根据提供的文件名"XStream-...

    XML与JAVA程序设计大全(光盘源文件)

    在Java中,JAXB(Java Architecture for XML Binding)和JDOM等库则简化了XML与Java对象之间的映射,使得数据交换更为便捷。此外,XSLT(Extensible Stylesheet Language Transformations)用于XML到XML的转换,而...

    JAXB乱码问题解决

    在Java开发中,JAXB(Java Architecture for XML Binding)是一个用于将XML文档和Java对象之间进行绑定的技术。在处理XML文件时,特别是涉及到序列化和反序列化时,可能会遇到字符编码问题,即所谓的“乱码”。这个...

    xml文件自动转成java对象工具

    5. **生成序列化和反序列化代码**:为了方便XML数据和Java对象之间的转换,工具还会生成解析XML和生成XML的代码,通常是基于JAXB(Java Architecture for XML Binding)或其他类似库。 除了XSD转Java,有些工具还...

    XML_JAVA指南

    总的来说,“XML_JAVA指南”应该涵盖了XML和Java之间的各种交互方式,包括解析、生成、验证和转换XML,以及使用JAXB进行对象-XML绑定。通过学习这些技术,开发者可以更好地在Java应用程序中集成和处理XML数据。

Global site tag (gtag.js) - Google Analytics