0

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

1 Answer 1

1

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....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.