【问题标题】:JAXB ignores @XmlAttribute annotationJAXB 忽略 @XmlAttribute 注释
【发布时间】:2021-05-11 11:37:37
【问题描述】:

JAXB 似乎忽略了@XmlAttribute 注释并且没有填充attributeNameattributeValue 属性。 你能帮我解决这个问题吗?

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Product>
    <ProductCode>PRD191_5</ProductCode>
    <AttrList>
        <element Name="Toy Type" Value="Quadrocopter"/>
        <element Name="Engine Type" Value="Electric Engine"/>
        <element Name="Build Type" Value="Ready-To-Fly"/>
    </AttrList>
</Product>

Java 类:

@XmlRootElement(name = "Product")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
    
    @XmlElement(name = "ProductCode")
    private String productCode;

    @XmlElement(name = "AttrList")
    private List<Attribute> attrList = null;
}
@XmlRootElement(name = "element")
@XmlAccessorType(XmlAccessType.FIELD)
public class Attribute {

    @XmlElement(name="element")
    @Column
    private String element;

    @XmlAttribute(name = "Name", required=true)
    @Column
    private String attributeName;

    @XmlAttribute(name = "Value", required=true)
    @Column
    private String attributeValue;
}

Maven 依赖:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

【问题讨论】:

    标签: java xml annotations jaxb


    【解决方案1】:

    您的模型定义中有一些错误:attrList 属性的@XmlElement 应设置为element(重复自身的元素),而包装器元素的名称&lt;AttrList&gt; 应传达带有@XmlElementWrapper 注释:

    @XmlRootElement(name = "Product")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Product {
        
        @XmlElement(name = "ProductCode")
        private String productCode;
        
        @XmlElementWrapper(name = "AttrList")
        @XmlElement(name = "element")
        private List<Attribute> attrList = null;
    }
    

    您还应该删除 Java Bean 属性 Attribute#element,因为它表示 &lt;element&gt; 标记的名为 &lt;element&gt; 的子元素。

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2011-11-13
      • 2012-07-16
      • 2011-09-15
      相关资源
      最近更新 更多