使用jaxb解析复杂的xml属性并生成对象模型

时间:2015-07-03 13:36:27

标签: java xml jaxb jaxb2

我的XML看起来像这样

<?xml version="1.0" ?>
<subjectAreaGroup>
    <subjectArea>
        <myObject>
            <layout columnNum="3" />
            <column name="ID" value="101"/>
            <column name="NAME" value="xyz"/>
            <column name="AGE" value="25" />
        </myObject>
    </subjectArea>
</subjectAreaGroup>

在这里,我必须处理复杂的属性并制作对象模型。你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用gson-xml。 GsonXml是一个小型库,允许使用Google Gson库进行XML反序列化。主要思想是将XML拉解析器事件流转换为JSON令牌流。

答案 1 :(得分:0)

您可以使用将对象转换为xml的JAXB编组,反之亦然示例,将客户对象转换为XML文件。

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}



try {
        Customer customer = new Customer();
        customer.setId(100);
        customer.setName("student");
        customer.setAge(29);
    File file = new File("C:\\file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();


        // output pretty printed


jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);


    jaxbMarshaller.marshal(customer, file);
    jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
    e.printStackTrace();
      }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
    <age>29</age>
    <name>student</name>
</customer>

类似于JAXB编组示例,将客户对象转换为XML文件。

try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
        System.out.println(customer);

      } catch (JAXBException e) {
        e.printStackTrace();
      }
相关问题