现在的位置: 首页 > 综合 > 正文

JAXB解析xml

2017年11月30日 ⁄ 综合 ⁄ 共 1702字 ⁄ 字号 评论关闭

大家知道xml常用的解析方式有DOM, SAX, StAX三种.如果使用这几种中的一种解析, 显然还是比较麻烦的.  可以使用JAXB(Java Architecture for XML Binding)

Person  
public class Person implements Serializable {  
    private String name;  
  
    private Integer age;  
  
    private char sex;  
  
    public Person() {  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public Integer getAge() {  
        return age;  
    }  
  
    public void setAge(Integer age) {  
        this.age = age;  
    }  
  
    public char getSex() {  
        return sex;  
    }  
  
    public void setSex(char sex) {  
        this.sex = sex;  
    }  
  
}  
  
@XmlRootElement(name = "persons")  
public class Persons extends ArrayList<Person> { // 泛化, 聚合  
  
    @XmlElement(name = "person")  
    public List<Person> getPersons() {  
        return this;  
    }  
}  
  
写xml  
public static void main(String[] args) {  
        try {  
            // javax.xml.bind.JAXBException: class com.fjh658.pojo.Persons nor  
            // any of its super class is known to this context.  
            JAXBContext cxt = JAXBContext.newInstance(Persons.class);  
            Marshaller marshaller = cxt.createMarshaller();  
  
            Persons persons = new Persons();  
            for (int i = 0; i < 50; i++) {  
                Person p = new Person();  
                p.setName("zhangsan" + i);  
                p.setAge(20 + i);  
                p.setSex('1');  
  
                persons.add(p);  
            }  
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串  
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 默认false表示xml指令存在  
  
            // marshaller.marshal(persons, System.out);  
            marshaller.marshal(persons, new File("./test.xml"));  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
  
    }  
  
读xml  
public class ReadTest {  
  
    public static void main(String[] args) {  
        try {  
            JAXBContext cxt = JAXBContext.newInstance(Persons.class);  
            Unmarshaller unmarshaller = cxt.createUnmarshaller();  
            List<Person> persons = (List<Person>) unmarshaller.unmarshal(new File("./test.xml"));  
  
            if (persons != null) {  
                for (Person p : persons) {  
                    if (p != null) {  
                        System.out.println(p.getName());  
                    }  
                }  
            }  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
  
    }  
} 

抱歉!评论已关闭.