jaxb读写xml小例子

前端之家收集整理的这篇文章主要介绍了jaxb读写xml小例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用maven构建工程,在pom.xml加入如下依赖:

<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1.13</version>
</dependency>

//一个Person类:

package com.mycomp.jaxb;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="person")
public class Person implements Serializable {

private static final long serialVersionUID = 1L;

private String name;

private Integer age;

private String sex;

public Person() {

}

public Person(String name,Integer age,String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}

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 String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

}

//测试读写方法的主类

package com.mycomp.jaxb;


import java.io.File;

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


public class App {

//写入xml的方法

private static void writeXml(Person person,File file) {
try {
JAXBContext cxt = JAXBContext.newInstance(Person.class);
Marshaller marshaller = cxt.createMarshaller();
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(person,file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
//读取xml的方法
private static void readXml(File file){
try {
JAXBContext cxt = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = cxt.createUnmarshaller();
Person person = (Person)unmarshaller.unmarshal(file);
if (person != null) {
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.getSex());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void main( String[] args ){
File file = new File("d:/test.xml");
Person person = new Person("张三",20,"男");
writeXml(person,file);
readXml(file);
}

}

原文链接:https://www.f2er.com/xml/297296.html

猜你在找的XML相关文章