如何从Java类生成以下XML,即具有属性和内容的XML元素
<?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;
}
}
我的输出如下
<?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>
现在如何在Java类中使用任何额外的标签/成员变量设置标题?
提前致谢
答案 0 :(得分:0)
使用 @XMLValue 注释实现此目的
<强> 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;
}
}
已在链接处回答 answered here....