我想生成以下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>我正在使用下面的pojo,它负责开始和结束,因为它们是固定的属性名称,但我有"testArticle","Endpoint","Chemcial“等,它们本质上是动态的,以及它们的值,我不确定如何处理。
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;
}
}发布于 2021-05-05 02:21:54
如果您知道adavance中的XML属性名称TestArticle、Chemical和Endpoint,那么您可以在WordPOJO Java类中将这些属性表示为附加属性:
@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)注意,您还需要通过localName = "..."显式地指定XML名,以匹配您的XML内容。(另请参阅javadoc of @JacksonXmlProperty。)如果您不这样做,那么Jackson将隐式地选择从您的Java属性名称(testArticle、chemical、endpoint)派生的XML名,这些名称与您的实际XML内容不匹配。
如果XML属性是真正动态的,并且您事先不知道它们,那么您将需要使用@JsonAnyGetter和@JsonAnySetter。请参阅javadoc of @JsonAnyGetter和JsonAnySetter。
不要对注释名称中的Json感到恼火。Jackson可以处理JSON和XML以及更多格式。对于JSON,您可以使用ObjectMapper。对于XML,您可以使用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;
}https://stackoverflow.com/questions/67389172
复制相似问题