如何使用jaxB或任何其他更好的方法将xml属性值映射到java类属性?

时间:2014-07-11 12:25:12

标签: java xml jaxb

这是我的test.xml,我想将属性名称值,即bookid,bookname和noOfPages标记为Book.java类的属性

<?xml version="1.0" encoding="UTF-8"?>
<tns:class xmlns:tns="http://www.example.org/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/test test.xsd ">
<attr name="bookid" primary="true"/>
<attr name="bookname" primary="false"/>
<attr name="noOfPages" primary="false"/>
<attr name="auth_name" primary="false"/>
</tns:class>

Book.java

package com.srl.rotelearning.test;

public class Book {

    private int bookId;
    private String bookname;
    private int noOfPages;

    public int getBookId() {
        return bookId;
    }

    public int getNoOfPages() {
        return noOfPages;
    }

    public void setNoOfPages(int noOfPages) {
        this.noOfPages = noOfPages;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

}

我尝试使用JAXB,但我认为我们可以将属性名称映射到类属性。如何将xml属性值映射到我的类属性?  plz给出详细信息,作为使用xml的新手谢谢:)

1 个答案:

答案 0 :(得分:1)

EclipseLink JAXB (MOXy)中,我们通过@XmlPath扩展程序

提供此行为
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlAccessorType(XmlAccessType.FIELD)
public class Book {

    @XmlPath("attr[@name='bookid']/text()")
    private int bookId;

    @XmlPath("attr[@name='bookname']/text()")
    private String bookname;

    @XmlPath("attr[@name='noOfPages']/text()")
    private int noOfPages;

}

了解更多信息

我在博客上写了更多关于此用例的内容: