Product文件:
package com.it.bean;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(namespace="http://localhost/xml/product", name="product")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="productType", namespace="http://localhost/xml/product")
public class Product
{
@XmlAttribute(required=true)
private Integer id;
@XmlElement(required=true)
private String name;
@XmlElement(type=String.class,name="mail")
private List
public List
return mails;
}
public void setMails(List
this.mails = mails;
}
public Product() {}
public Product(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试文件:
package JUnit4.test;
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 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.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.it.bean.Product;
public class RunProduct000000
{
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
}
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
@Test
public void buildXMLFileFromJavaObject() {
try {
JAXBContext jc = JAXBContext.newInstance(Product.class);
Marshaller m = jc.createMarshaller();
OutputStream s = new FileOutputStream(new File(".","product.xml"));
//StringWriter writer = new StringWriter();
Product p = new Product(15, "足球");
p.getMails().add("你啊好哦");
p.getMails().add("粑粑意义");
p.getMails().add(2, "8514796");
p.getMails().add("4444444");
m.marshal(p, os);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void readXMLFileToJavaObject() {
try {
JAXBContext jc = JAXBContext.newInstance(Product.class);
Unmarshaller m = jc.createUnmarshaller();
InputStream in = new FileInputStream(new File(".","product.xml"));
Product product = (Product)m.unmarshal(in);
System.out.println("id="+ product.getId()+",name="+ product.getName());
List
mails=product.getMails();
for (String mail:mails)
{
System.out.println(mail);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/20929645/viewspace-609763/ ,如需转载,请注明出处,否则将追究法律责任。