jaxb xml 解析出 list对象

jaxb想直接解析出list对象, 不用在list对象上再去包装一层对象

首先定义一个通用的包装对象

<pre>

import java.util.*;

import javax.xml.bind.annotation.XmlAnyElement;

public class Wrapper<T> {

    private List<T> items;

    public Wrapper() {

        items = new ArrayList<T>();

    }

    public Wrapper(List<T> items) {

        this.items = items;

    }

    @XmlAnyElement(lax=true)

    public List<T> getItems() {

        return items;

    }

}

</pre>

然后是我们的xml

<pre>

<?xml version="1.0" encoding="UTF-8"?>

 <Items>

     <Item item="Check patient name, gender, age" needData="true" >

     <Book name="book1" />

     <Book name="book2" />

</Item>

     <Item item="Check patient name, gender, age" needData="true" >

     <Book name="book1" />

     <Book name="book2" />

</Item>

 </Items>

</pre>

java类

<pre>

@XmlRootElement(name="Item")

public class Item {

private String item;

private boolean needData;

private List<Book> books;

@XmlAttribute(name = "item")

public String getItem() {

return item;

}

public void setItem(String item) {

this.item = item;

}

@XmlAttribute(name = "needData")

public boolean isNeedData() {

return needData;

}

public void setNeedData(boolean needData) {

this.needData = needData;

}

@XmlElements(value = { @XmlElement(name = "Book", type = Book.class) })

public List<Book> getBooks() {

return books;

}

public void setBooks(List<Book> books) {

this.books = books;

}

}

@XmlRootElement(name="Book")

public class Book {

private String name;

@XmlAttribute(name = "name")

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

</pre>

jaxb代码

<pre>

    private static <T> List<T> unmarshal(javax.xml.bind.Unmarshaller unmarshaller,

            Class<T> clazz, String xmlLocation) throws JAXBException {

        StreamSource xml = new StreamSource(xmlLocation);

        Wrapper<T> wrapper = (Wrapper<T>) unmarshaller.unmarshal(xml,

                Wrapper.class).getValue();

        return wrapper.getItems();

    }

public static  <T> List parseXmlToList(Class<T> topLevelClass, String xmlLocation) throws Exception {

        JAXBContext jc = JAXBContext.newInstance(Wrapper.class,topLevelClass);

        

        // Unmarshal

        Unmarshaller unmarshaller = jc.createUnmarshaller();

        List<T> list = unmarshal(unmarshaller, topLevelClass, xmlLocation);

        return list;

}

</pre>

最后是客户端代码

<pre>

List<Item> addresses = parseXmlToList(Item.class, "WardCheck.xml");

        System.out.println(addresses);

        System.out.println(addresses.get(0).getItem());

        List<Book> list = addresses.get(0).getBooks();

        System.out.println(list.size());

        System.out.println(addresses.get(0).getBooks().get(0).getName());

</pre>

来自link http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html

猜你喜欢

转载自renxiangzyq.iteye.com/blog/2195855