我有一个带有信封的 xml,在信封中有一个标题,在标题中有一个名为 Period 的元素,带有 Startdate 和 Enddate。但在某些情况下,它们被称为 StartDate 和 EndDate。是否有某种方式可以告诉 JAXB 在解组时同时查找两者?
我已经有一个类信封,其中包含我需要的所有元素父类的一堆类,如果需要,每个父元素都有子元素。其中之一是类 Period ,其中有两个@XmlElement public String ***date
。
我用 unmarshall 解析它,然后访问我的 InsertProcessor 中的数据以将它们放入查询中并将其保存到数据库中。
我尝试使用@XmlElements({})
,但没有奏效:
@XmlElements({
@XmlElement(name = "Startdate", type = Startdate.class),
@XmlElement(name = "StartDate", type = StartDate.class)
})
private DateStart startdate;
@XmlElements({
@XmlElement(name = "Enddate", type = Enddate.class),
@XmlElement(name = "EndDate", type = EndDate.class)
})
private DateEnd enddate;
public Startdatum getStartdate() {
return startdate;
}
public Stopdatum getEnddate() {
return enddate;
}
abstract class DateStart{}
private class Startdate extends DateStart{}
private class StartDate extends DateStart{}
abstract class DateEnd{}
private class Enddate extends DateEnd{}
private class EndDate extends DateEnd{}
试图在 InsertProcessor.java 中访问它env.Header.Period.getStartdate();
IDE 响应Incompatible types. Required String, Found Parser.Startdatum
示例.xml
<envelope>
<data>
<msgcode>441</msgcode>
<msgdate>201903151120000</msgdate>
</data>
<Message>
<Header>
<Period>
<Startdate>2018-05-01</Startdate> <!-- can also be StartDate -->
<Enddate>2018-05-31</Enddate> <!-- can also be EndDate -->
</Period>
</Header>
</Message>
</envelope>
解析器.java
public class Parser {
public static Envelope parse (String xml) throws JAXBException, SAXException {
JAXBContext jc;
jc = JAXBContent.newInstance(Envelope.class)
Unmarshaller u = jc.createUnmarshaller();
...
InputSource is = new InputSource(new StringReader(xml));
return (Envelope) u.unmarshal(new SAXSource(inFiler, inputSource));
}
@XmlRootElement(name="Envelope")
public static class Envelope {
@XmlElement(name = "Data")
public Data Data;
@XmlElement(name = "Message")
public Message Message;
}
...
public static class Message {
@XmlElement(name = "Header")
public Header Header;
...
}
public static class Header {
@XmlElement(name = "Period")
public Period Period;
...
}
public static class Period {
@XmlElement(name = "Startdate")
public String Startdate;
@XmlElement(name = "Enddate")
public String Enddate;
}
...
}
插入处理器.java:
public class InsertProcessor {
public void process(String xml) throws Exception {
Parser.Envelope env = Parser.parse(xml);
String id = env.Header.Identification;
...
String Startdate = env.Header.Period.Startdate;
String Enddate = env.Header.Period.Enddate;
try (Connection c = Db.getConnection()) {
PreparedStatement ps = c.prepareStatement("insert into...");
ps.setString(1, id)
...
ps.setString(9, Startdate);
ps.setString(10, Enddate);
ps.execute();
}
}
所以我需要获取开始/结束日期或开始/结束日期。现在我刚刚开始/结束日期