1. 程式人生 > >java成神之——jaxb操作xml的基本使用

java成神之——jaxb操作xml的基本使用

bind jaxb val element return setters enc class depend

  • JAXB
    • 依賴
    • 讀取xml配置
    • 寫配置
    • 自定義寫配置
  • 結語

JAXB

依賴

<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.1</version>
</dependency> 

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

讀取xml配置

User類
@XmlRootElement
public class User{
    private Integer id;
    private String name;
    // gettters and setters
}

xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <id>1</id>
    <name>葉</name>
</user>

獲取配置
User user = JAXB.unmarshal(new File("C:\\Users\\26401\\Desktop\\demo.xml"), User.class);

寫配置

User user = new User();
user.setName("小葉");
user.setId(2);
JAXB.marshal(user, new File("C:\\Users\\26401\\Desktop\\demo.xml"));

結果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <id>2</id>
    <name>小葉</name>
</user>

自定義寫配置

@XmlAccessorType(XmlAccessType.NONE) 
public class User{

    @XmlElement
    private Integer id;

    @XmlElement(name="username")
    private String name;

    @XmlAttribute
    private String nameDescribe;

    @XmlTransient
    private Integer age;

    @XmlElement
    public Integer getPassAge() {
        return age;
    }

    public void setPassAge(Integer val) {} 

    public User(){}

    public User(Integer id, String name, String nameDescribe, Integer age) {
        this.id = id;
        this.name = name;
        this.nameDescribe = nameDescribe;
        this.age = age;
    }
}

寫數據
User user = new User(1, "葉家偉", "用戶姓名", 18);
JAXB.marshal(user, new File("C:\\Users\\26401\\Desktop\\demo.xml"));

結果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user nameDescribe="用戶姓名">
    <id>1</id>
    <username>葉家偉</username>
    <passAge>18</passAge>
</user>

結語

本文章是java成神的系列文章之一

如果你想知道,但是本文沒有的,請下方留言

我會第一時間總結出來並發布填充到本文

java成神之——jaxb操作xml的基本使用