Pratap A.K
Pratap A.K

Reputation: 4517

Spring Boot XML element with attribute and content

How to generate below XML from Java class i.e XML element with attribute and content

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookstore>
    <book category="gaming">
        <author>Pratap A K</author>
        <price>100र</price>
        <title lang="en">some title</title>
        <year>2017</year>
    </book>
</bookstore>

Controller.java

@RequestMapping(value = "/xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Bookstore getXMLData() {

        Bookstore bookstore = new Bookstore();
        Book book = new Book();

        book.setCategory("gaming");
        book.setAuthor("Pratap A K");
        book.setPrice("100र");
        book.setYear("2017");

        Title title = new Title();
        title.setLang("kannada");
        book.setTitle(title);

        bookstore.setBook(book);

        return bookstore;
    }

Bookstore.java

@XmlRootElement(name="bookstore")
public class Bookstore {

    private Book book;
    //getters and setters   
}

Book.java

public class Book {

    private String category;
    private String author;
    private String year;
    private String price;
    private String lang;
    private Title title;

    @XmlAttribute(name="category")
    public String getCategory() {
        return category;
    }
    //getters and setters continue...

}

Title.java

public class Title {

    private String lang;

    @XmlAttribute(name="lang")
    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang = lang;
    }
}

I am getting output as below

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookstore>
    <book category="gaming">
        <author>Pratap A K</author>
        <price>100र</price>
        <title lang="en"/>
        <year>2017</year>
    </book>
</bookstore>

Now How can I set title whithout using any extra tags / member variable in Java class?

Thanks in advance

Upvotes: 0

Views: 10629

Answers (1)

Pratap A.K
Pratap A.K

Reputation: 4517

Achieved this by using @XMLValue annotation

Title.java

public class Title {

    private String lang;
    private String value;

    @XmlValue
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @XmlAttribute
    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang = lang;
    }
}

Already answered at link answered here....

Upvotes: 1

Related Questions