简体   繁体   English

使用标记名称的多个选项将XML映射到Java

[英]Map XML to Java with multiple option for tag names

I need to parse an XML file then map it to a Java object. 我需要解析一个XML文件,然后将其映射到Java对象。 So far, I do it with an annotated POJO : 到目前为止,我使用带注释的POJO来实现:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"title", "id", "eventList"})
@XmlRootElement(name = "MyClass")
public class MyClass {

  @XmlElement(name = "Title", required = true)
  protected String title;

  @XmlElement(name = "Id", required = false)
  protected String id;

  @XmlElement(name = "EventList", required = true)
  protected EventList eventList;
}

Then unmarshall it with JAXB : 然后用JAXB解组它:

MyClass myObj = (MyClass) unmarshaller.unmarshal(new StreamSource(fis))

Problem : Sometimes, my customer send files with slightly different tag names (for example, Eventlist instead of EventList ) 问题 :有时,我的客户发送的标签名称稍有不同(例如, Eventlist而不是EventList

Is there an option to allow both names for a tag? 是否有允许标签同时使用两个名称的选项? Up to now, I solve this problem by giving 2 attributes in the POJO : 到目前为止,我通过在POJO中提供2个属性来解决此问题:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"title", "id", "eventList"})
@XmlRootElement(name = "MyClass")
public class MyClass {

  @XmlElement(name = "Title", required = true)
  protected String title;

  @XmlElement(name = "Id", required = false)
  protected String id;

  @XmlElement(name = "EventList", required = false)
  protected EventList eventList;

  @XmlElement(name = "Eventlist", required = false)
  protected EventList eventlist;
}

This is hard to maintain and forbids me to use the 'required' attribute. 这很难维护,并且禁止我使用“ required”属性。 Do you have a better solution? 您有更好的解决方案吗?

I am not sure there is an option to add multiple names, but what you can do is: 我不确定是否可以添加多个名称,但是您可以执行以下操作:

make the fields private and add getters and setters for them. 将字段设为私有,并为其添加getter和setter。 You can make 2 getters and setters for the eventlist-field and annotate them with different names. 您可以为eventlist-field创建2个getter和setter并用不同的名称注释它们。 Since this field is not required, as I see, there will be no problem. 如我所见,由于不需要此字段,因此不会有问题。

Although.. as I see now, the problem is actually solved. 虽然..正如我现在看到的,问题实际上已经解决了。 See here: JAXB: unmarshalling xml with multiple names for the same element 参见此处: JAXB:同一元素的多个名称的XML编组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM