
本教程详细介绍了如何使用java jaxb库将java对象转换为具有特定格式的xml文件,特别是如何将java对象的字段映射为xml元素的属性而非子元素。通过 `@xmlattribute` 注解、`@xmlrootelement` 和 `@xmlaccessortype`,结合一个根元素包装类,您可以精确控制xml的输出结构,实现所需的属性化xml格式,并确保xml输出的整洁可读性。
在许多企业级应用中,将Java对象序列化为XML文件是一项常见的任务。然而,XML的结构多种多样,有时我们需要将Java对象的字段映射为XML元素的属性(Attribute),而非默认的子元素(Element)。例如,我们可能需要生成如下所示的XML结构:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person
            name="Nick"
            birthday = "09.03.1814"/>
</persons>或者:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person surname="Sd" name="aaa" birthday = "09.03.1814"/>
</persons>本教程将指导您如何使用Java Architecture for XML Binding (JAXB) 实现这一目标。
JAXB是Java EE的一部分,提供了一种将Java对象映射到XML表示的便捷方式。它通过一系列注解来控制Java对象与XML结构之间的绑定关系。
立即学习“Java免费学习笔记(深入)”;
为了生成上述XML结构,我们需要定义两个Java类:一个表示单个person元素,另一个作为persons根元素的包装器。
这个类将包含name、surname和birthday字段,并使用@XmlAttribute注解将它们映射为XML属性。
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
// @XmlRootElement(name = "person") 定义了该对象在XML中对应的根元素名为 "person"
// @XmlAccessorType(XmlAccessType.FIELD) 指示JAXB通过字段访问数据,
// 这对于将字段映射为属性至关重要。
@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
public class DtoPerson {
    // @XmlAttribute(name = "name") 将Java字段name映射为XML属性name
    @XmlAttribute(name = "name")
    private String name;
    // @XmlAttribute(name = "surname") 将Java字段surname映射为XML属性surname
    // 此字段是可选的,根据XML格式需求可有可无
    @XmlAttribute(name = "surname")
    private String surname;
    // @XmlAttribute(name = "birthday") 将Java字段birthday映射为XML属性birthday
    @XmlAttribute(name = "birthday")
    private String birthday;
    // 无参构造函数是JAXB反序列化所必需的
    public DtoPerson() {}
    // 构造函数,方便创建对象
    public DtoPerson(String name, String birthday) {
        this.name = name;
        this.birthday = birthday;
    }
    public DtoPerson(String name, String surname, String birthday) {
        this.name = name;
        this.surname = surname;
        this.birthday = birthday;
    }
    // Getters and Setters (JAXB在XmlAccessType.FIELD模式下不需要,但良好实践建议保留)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "DtoPerson{" +
               "name='" + name + '\'' +
               ", surname='" + surname + '\'' +
               ", birthday='" + birthday + '\'' +
               '}';
    }
}由于JAXB不能直接将List对象作为XML的根元素进行编组,我们需要创建一个包装类来包含DtoPerson对象的列表。
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
// @XmlRootElement(name = "persons") 定义了该对象在XML中对应的根元素名为 "persons"
@XmlRootElement(name = "persons")
@XmlAccessorType(XmlAccessType.FIELD) // 同样通过字段访问
public class PersonsWrapper {
    // @XmlElement(name = "person") 指示列表中每个元素都应被编组为名为 "person" 的XML子元素
    @XmlElement(name = "person")
    private List<DtoPerson> personList;
    // 无参构造函数是JAXB反序列化所必需的
    public PersonsWrapper() {}
    public PersonsWrapper(List<DtoPerson> personList) {
        this.personList = personList;
    }
    public List<DtoPerson> getPersonList() {
        return personList;
    }
    public void setPersonList(List<DtoPerson> personList) {
        this.personList = personList;
    }
}现在,我们有了数据模型,可以编写JAXB编组(Marshalling)代码来生成XML文件。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class XmlGenerator {
    /**
     * 根据提供的DtoPerson列表生成XML文件。
     *
     * @param persons 要编组的DtoPerson对象列表
     * @param outputPath 生成XML文件的路径
     */
    public static void createXmlFromPersons(List<DtoPerson> persons, String outputPath) {
        try {
            // 1. 创建PersonsWrapper对象,将DtoPerson列表包装起来
            PersonsWrapper personsWrapper = new PersonsWrapper(persons);
            // 2. 创建JAXBContext实例。JAXBContext需要知道要编组的根元素类。
            // 这里是PersonsWrapper.class,因为它将作为XML的根。
            JAXBContext jaxbContext = JAXBContext.newInstance(PersonsWrapper.class);
            // 3. 创建Marshaller对象,用于将Java对象转换为XML
            Marshaller marshaller = jaxbContext.createMarshaller();
            // 4. 设置Marshaller属性,使其生成格式化(美观)的XML输出
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 5. 将PersonsWrapper对象编组到文件
            File file = new File(outputPath);
            marshaller.marshal(personsWrapper, file);
            System.out.println("XML文件已成功创建于: " + file.getAbsolutePath());
        } catch (JAXBException e) {
            System.err.println("创建XML文件时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("XML生成失败", e);
        }
    }
    public static void main(String[] args) {
        // 示例用法
        List<DtoPerson> personList = new ArrayList<>();
        // 添加第一个示例人员 (只有name和birthday)
        personList.add(new DtoPerson("Nick", "09.03.1814"));
        // 添加第二个示例人员 (包含surname, name和birthday)
        personList.add(new DtoPerson("John", "Doe", "15.07.1990"));
        // 添加更多人员
        personList.add(new DtoPerson("Jane", "Smith", "22.11.1985"));
        // 调用方法生成XML文件
        createXmlFromPersons(personList, "persons_output.xml");
    }
}运行 main 方法后,persons_output.xml 文件将被创建,内容如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persons>
    <person name="Nick" birthday="09.03.1814"/>
    <person name="John" surname="Doe" birthday="15.07.1990"/>
    <person name="Jane" surname="Smith" birthday="22.11.1985"/>
</persons>这个输出完美符合我们预期的属性化XML格式。
通过本教程,您应该已经掌握了如何使用JAXB的注解(特别是@XmlAttribute、@XmlRootElement和@XmlAccessorType)来精确控制Java对象到XML的映射,实现将Java对象字段转换为XML属性的特定格式需求。JAXB提供了一种强大且灵活的方式来处理Java与XML之间的数据绑定,理解这些核心注解和最佳实践对于高效地进行XML数据处理至关重要。
以上就是Java JAXB教程:精确控制XML结构,将对象字段转换为XML属性的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号