Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map xml attribute values to java class attributes using jaxB or any other better method?

Tags:

java

xml

jaxb

this is my test.xml and i want to tag attribute name values i.e bookid, bookname and noOfPages to attributes of Book.java class

<?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;
    }

}

i tried using JAXB but i think we can map attribute names to class attributes. how do i map xml attribute values to my class attributes? plz give ans in detail as m new to using xml thanks :)

like image 807
Sharmishtha Kulkarni Avatar asked Feb 06 '26 14:02

Sharmishtha Kulkarni


1 Answers

In EclipseLink JAXB (MOXy) we offer this behaviour through our @XmlPath extension

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;

}

For More Information

I have written more about this use case on my blog:

  • http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
like image 111
bdoughan Avatar answered Feb 09 '26 09:02

bdoughan