我正在尝试使用JAXB解组已存在(且不可更改)的xml格式。问题归结为需要<DATA>
标记的内容,但是我需要的数据可以直接位于<DATA>
下,也可以位于<DATA><OPTIONAL1>
或<DATA><OPTIONAL1><OPTIONAL2>
下。 xml具有may属性和标签,但是我将问题简化如下:
<SEC>
<RECORD id="1">
<SOMEOTHERTAG>Other data</SOMEOTHERTAG>
<DATA>Data I want</DATA>
<SOMEOTHERTAG2>Other data</SOMEOTHERTAG2>
</RECORD>
<RECORD id="2">
<SOMEOTHERTAG>Other data</SOMEOTHERTAG>
<SOMEOTHERTAG2>Other data</SOMEOTHERTAG2>
<SOMEOTHERTAG3>Other data</SOMEOTHERTAG3>
<DATA>
<OPTIONAL1>Data I want</OPTIONAL1>
</DATA>
</RECORD>
<RECORD id="3">
<SOMEOTHERTAG>Other data</SOMEOTHERTAG>
<DATA>
<OPTIONAL1>
<OPTIONAL2>Data I want</OPTIONAL2>
</OPTIONAL1>
</DATA>
</RECORD>
<RECORD id="4">
<DATA>
<OPTIONAL1>Data I want</OPTIONAL1>
</DATA>
</RECORD>
<RECORD id="5">
<SOMEOTHERTAG3>Other data</SOMEOTHERTAG3>
<DATA>Data I want</DATA>
</RECORD>
<RECORD id="6">
<DATA>Data I want</DATA>
</RECORD>
</SEC>
这是我当前的代码(此场景再次简化):
@XmlRootElement(name="SEC")
public class SECModel {
@XmlElement(name="RECORD")
List<RecordModel> recordList;
@Override
public String toString() {
return "SECModel [recordList=" + recordList + "]";
}
@XmlTransient
public List<RecordModel> getRecordList() {
return recordList;
}
public void setRecordList(List<RecordModel> recordList) {
this.recordList = recordList;
}
}
public class RecordModel {
@XmlAttribute(name="id")
private String id;
@XmlElement(name="SOMEOTHERTAG")
private String someOtherTag;
@XmlElement(name="SOMEOTHERTAG2")
private String someOtherTag2;
@XmlElement(name="SOMEOTHERTAG3")
private String someOtherTag3;
// What to put here?
private String data;
@Override
public String toString() {
return "RecordModel [id=" + id + ", data=" + data + "]";
}
@XmlTransient
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlTransient
public String getSomeOtherTag() {
return someOtherTag;
}
public void setSomeOtherTag(String someOtherTag) {
this.someOtherTag = someOtherTag;
}
@XmlTransient
public String getSomeOtherTag2() {
return someOtherTag2;
}
public void setSomeOtherTag2(String someOtherTag2) {
this.someOtherTag2 = someOtherTag2;
}
@XmlTransient
public String getSomeOtherTag3() {
return someOtherTag3;
}
public void setSomeOtherTag3(String someOtherTag3) {
this.someOtherTag3 = someOtherTag3;
}
@XmlTransient
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
我试图使泛型类具有3个子类来处理专门针对数据元素的每种情况,并使用@XmlElements()将XML解组,如下所示:
@XmlElements({ @XmlElement(name = "DATA", type = DataModelOpt1.class, required = false),
@XmlElement(name = "DATA", type = DataModelOpt2.class, required = false)})
private DataModelGeneric data;
但是,Jaxb似乎想将每个标签解组到DataModelOpt2.class中-也许是因为它显示在该列表的最后?正确的方法是什么?