java - 如何编写具有属性和值的 JAXB 对象

标签 java xml jaxb

这是我想要的 XML 结构

<Outer type="good" id="1">
  <Uid>123</Uid>
  <Name>Myself</Name>
  <Inner type="bad">This Value</Inner>
</Outer>

这是我的对象。

@XmlAccessorType(XMLAccessType.FIELD)
@XmlType(name="Outer", propOrder = {
  "uid"
  "name"
  "inner"
})
public class Outer{
  @XmlElement(name = "Uid")
  protected String uid;
  @XmlElement(name = "Name")
  protected String name;
  @XmlElement(name = "Inner")
  protected Inner inner;

  public static class Inner{
    @XmlAttribute
    private String type;
    @XmlValue
    private String value;

    //setters & getters for both
  }

  //setters & getters for all the elements
}

现在我在类里面正在做

Outer o = new Outer();
o.setUid/ID/Type/Name() ; //all the setter
Inner i - new Inner();
i.setValue("This Value");
i.setType("bad");

当我运行这个时,我得到了

If a class has @XmlElement property, it cannot have @XmlValue property.

Class has two properties of the same name "type" (This one is for the Source class)

Class has two properties of the same name "value" (This one is for Source class too)

发生了什么事,我能做些什么来纠正这个问题?

谢谢

最佳答案

目前,JAXB 将两个字段(由于注释)和两对 get/set(由于默认访问器类型)作为属性进行威胁。所以你的类 Inner 有 4 个属性。

请为 Inner 类添加自己的访问器类型

   @XmlAccessorType(XmlAccessType.FIELD)
   public static class Inner
   {  

或者注释属性而不是字段

   public static class Inner
   {

      private String type;


      private String value;

      @XmlAttribute
      public String getType()
      {
         return type;
      }
      // setter setType

      @XmlValue
      public String getValue()
      {
         return value;
      }   
      // setter setValue
   }  

关于java - 如何编写具有属性和值的 JAXB 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23956058/

相关文章:

java - 最后抛出的异常如何包含先前抛出的异常?

java - 如何处理 doGet 或 doPost 中潜在的长时间操作?

java - ArrayList.remove(int) 与不同线程中的 ArrayList.remove(Object)

python - 在特定位置插入xml节点

javascript - javascript中的setTimeout不给浏览器 'breathing room'

xml - 它们是 Android Studio 的 "region-like"折叠功能吗

java - jaxb 抛出 javax.xml.bind.UnmarshalException : Expected elements are (none) only when running in osgi bundle

java - JAXB 将不需要的 namespace 声明附加到标记

java - 在 Android Studio 中使用 Java 居中 View

java - 如何在Java中为带有属性的自包含标签编写xml注释