I want to generate following xml:
<word start="1556" end="1564" TestArticle="36" Chemical="7">Ammonium</word>
<word start="1566" end="1584" Endpoint="36" Chemical="7" >per-fluorobutyrate</word>
<word start="1585" end="1586" TestArticle="37" >(</word>
I am using following pojo, which takes care of start and end as they are fixed attribute names, but I have "testArticle", "Endpoint", "Chemcial", etc which are dynamic in nature as well as there value, which I am not sure how to handle.
public class WordPOJO {
@JacksonXmlProperty(isAttribute = true)
String start;
@JacksonXmlProperty(isAttribute = true)
String end;
@JacksonXmlText
String str;
// not sure if this is the way to do it, but it not outputing in desired format
@XmlAnyElement(lax = true)
List<String> entityList;
public String getStart() {
return start;
}
public void setStart(String span) {
this.start = span;
}
public String getEnd() {
return end;
}
public void setEnd(String span) {
this.end = span;
}
public List<String> getEntityList()
{
return entityList;
}
public void setEntityList(List<String> entityList)
{
this.entityList = entityList;
}
//@JacksonXmlElementWrapper(useWrapping = false)
//@JacksonXmlProperty(localName = "word")
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
If you know the XML attribute names TestArticle
, Chemical
and Endpoint
in adavance, then you can represent these as additional properties in your WordPOJO
Java class:
@JacksonXmlProperty(isAttribute = true, localName = "TestArticle")
String testArticle;
@JacksonXmlProperty(isAttribute = true, localName = "Chemical")
String chemical;
@JacksonXmlProperty(isAttribute = true, localName = "Endpoint")
String endpoint;
// Getters and setters (omitted here for brevity)
Notice that you also need to explicitly specify the XML names by localName = "..."
) to match your XML content. (See also the javadoc of @JacksonXmlProperty
.) If you would not do this, then Jackson would implicitly pick up XML names derived from your Java property names ( testArticle
, chemical
, endpoint
) which would not match your actual XML content.
If the XML attributes are truly dynamic and you don't know them in advance, then you will need to use @JsonAnyGetter
and @JsonAnySetter
. See the javadoc of @JsonAnyGetter and JsonAnySetter .
Don't be irritated by Json
in the annotation names. Jackson can handle JSON and XML and many more formats. For JSON you use ObjectMapper
. And for XML you use XmlMapper
.
Map<String, Object> otherProperties = new HashMap<>();
@JsonAnySetter
public void setOtherProperty(String name, String value) {
otherProperties.put(name, value);
}
@JsonAnyGetter
public Map<String, Object> getOtherProperties() {
return otherProperties;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.