有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有更多名称的java JAXB@XmlElement

我有一个带有信封的xml,信封中有一个标题,标题中有一个名为Period的元素,带有Startdate和Enddate。但在某些情况下,它们被称为开始日期和结束日期。有没有什么方法可以告诉JAXB在解组时同时查找这两个选项

我已经有了一个类信封,里面有一堆类,用于所有我需要的元素父元素,如果需要,每个都有子元素。其中一个是课堂期间,其中有两个@XmlElement public String ***date

我用解组器解析它,然后访问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>

解析器。爪哇

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;
 }
...
}

嵌入式处理器。爪哇:

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();
  }
}

所以我需要得到开始/结束日期或开始/结束日期。现在我刚刚开始/结束日期


共 (0) 个答案