XML和Java对象之间的转换

前端之家收集整理的这篇文章主要介绍了XML和Java对象之间的转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

当xml文件和java对象对应起来的时候,使用一些工具类可以方便的实现xml和java对象之间的互相转化。

package me.mymilkbottles.JavaXML;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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

import org.junit.Ignore;
import org.junit.Test;

import me.mymilkbottles.pojo.User;

public class JavaXML {

    @Test
    @Ignore
    public void testJavaToXML() throws Exception {
        File file = new File("user.xml");
        // 创建JAXBContext上下文对象
        JAXBContext jaxbContext = JAXBContext.newInstance(UserClass.class);
        // 创建Marshaller转换对象
        Marshaller marshaller = jaxbContext.createMarshaller();
        UserClass userClass = new UserClass("user_name","pass_word",5.0001,7);
        marshaller.marshal(userClass,file);
    }

    @Test
    @Ignore
    public void testXMLToJava() throws Exception {
        File file = new File("user.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(UserClass.class);
        Unmarshaller marshaller = jaxbContext.createUnmarshaller();
        UserClass userClass = (UserClass) marshaller.unmarshal(file);
        System.out.println(userClass);
    }

    @Test
    @Ignore
    public void testComplexJavaToXML() throws Exception {
        File file = new File("user.xml");
        // 创建JAXBContext上下文对象
        JAXBContext jaxbContext = JAXBContext.newInstance(ComplexUser.class);
        // 创建Marshaller转换对象
        Marshaller marshaller = jaxbContext.createMarshaller();
        Address address = new Address();
        address.setAddressId(12345678);
        address.setCity("hello_city");
        address.setSchool("hello_school");

        List<User> list = new ArrayList<User>();
        for (int i = 0; i < 3; ++i) {
            User user = new User();
            user.setId(10001);
            user.setName("hello_user");
            user.setPassword("000036");
            list.add(user);
        }

        ComplexUser complexUser = new ComplexUser();
        complexUser.setId(199000);
        complexUser.setAddress(address);
        complexUser.setName("hello_complexUser");
        complexUser.setList(list);

        marshaller.marshal(complexUser,file);
    }

    @Test
    public void testXMlToJava() throws Exception {
        File file = new File("user.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(ComplexUser.class);
        Unmarshaller marshaller = jaxbContext.createUnmarshaller();
        ComplexUser userClass = (ComplexUser) marshaller.unmarshal(file);
        System.out.println(userClass);
    }
}

猜你在找的XML相关文章