Sreeragh A R
Sreeragh A R

Reputation: 3021

How to make base class field an attribute of xml schema of sub class using JAXB

Here is what i am doing:

This is my shape class which has id

public class Shape {
    private int id;

    @XmlAttribute
    public int getId(){
        return id;
    }

    public void setId(int no)
        id = no;
    }

}

This is my circle class which inherits shape class.

@XmlRootElement(name="Circle")
    public class Circle extends Shape {

      private int radius;

      public int getRadius() {
           return radius;

      }
      public void setRadius(int rad) {
          radius = rad;
      }


}

Generated pom file

<?xml version="1.0" encoding="UTF-8"?>
<Circle>
<id>1345</id>
<radius>5</radius>
</Circle>

I want this. Please note the id is an attribute not element as produced above.

<?xml version="1.0" encoding="UTF-8"?>
<Circle id=1345>
<radius>5</radius>
</Circle>

How can I go about doing this.

I am using java8 jaxb Any help!

Upvotes: 1

Views: 153

Answers (1)

Sumit Sagar
Sumit Sagar

Reputation: 352

hi Please try the Driver class as below.

public class Converter {

public static void main(String[] args) {
     Circle circle = new Circle();
      circle.setRadius(5);
      circle.setId(1234);
      try {

        File file = new File("Y:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Circle.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

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

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

}

Upvotes: 2

Related Questions