Jaxb 2将不同元素映射到相同属性

发布于 2024-09-08 07:07:41 字数 142 浏览 1 评论 0原文

我想知道这在 jaxb2 中是否可行。我有一个 xml 可以是 <元素>或<元素2>它永远不会在某个时候出现。它们都是 String 类型,我希望它映射到我的 java 类中的相同属性。 jaxb2 有没有办法配置它?

谢谢 查理

I wonder if this is possible in jaxb2. I have a xml that can be either < element > or < element2 > it will never apear at the some time. They are both of type String and I want it to map to the same property in my java class. Is there a way in jaxb2 to configure that?

Thanks
Charlie

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长途伴 2024-09-15 07:07:41

如果您尝试序列化回 XML 会发生什么?将使用哪个元素名称?

假设您只需要从 XML 反序列化为 Java,那么您可以通过注释 setter 方法而不是字段来完成此操作:

public class Bean {

   private String value;

   @XmlElement(name="element")
   public void setA(String value) {
      this.value = value;
   }

   @XmlElement(name="element2")
   public void setB(String value) {
      this.value = value;
   }
}

您可能还需要添加 getA()getB()< /code> 方法,以便 JAXB 正确识别设置器。

What would happen if you tried to serialize back to XML? Which element name would be used?

Assuming you only need to deserialize from XML to Java, then you can do this by annotating your setter methods instead of your fields:

public class Bean {

   private String value;

   @XmlElement(name="element")
   public void setA(String value) {
      this.value = value;
   }

   @XmlElement(name="element2")
   public void setB(String value) {
      this.value = value;
   }
}

You might also have to add getA() and getB() methods in order for JAXB to recognise the setters properly.

三生一梦 2024-09-15 07:07:41

你可以这样做:

@XmlElements({
    @XmlElement(name="command", type=CommandVO.class, namespace="http://chains.projetox.com.br/"),
    @XmlElement(name="script", type=ScriptVO.class, namespace="http://chains.projetox.com.br/")
})
private List<SubjectVO> commands;

其中:

public interface SubjectVO {}
public class CommandVO implements SubjectVO {}
public class ScriptVO implements SubjectVO {}

You can do something like that:

@XmlElements({
    @XmlElement(name="command", type=CommandVO.class, namespace="http://chains.projetox.com.br/"),
    @XmlElement(name="script", type=ScriptVO.class, namespace="http://chains.projetox.com.br/")
})
private List<SubjectVO> commands;

Where:

public interface SubjectVO {}
public class CommandVO implements SubjectVO {}
public class ScriptVO implements SubjectVO {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文