Jaxb2Marshaller and attributes

I have a problem using Jaxb2Marshaller to decouple XML attributes (primitive types). Here is an example:

<?xml version="1.0" encoding="UTF-8"?>
<request xmlns="...">
    <items>
        <item id="1"/>
        <item id="2"/>
        <item id="3"/>
    </items>
</request>

And the entity class:

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement(name = "request", namespace = "...")
@XmlType(name = "Request", namespace = "...")
public class Request {

    private List<Item> _items;

    @XmlElementWrapper(name = "items", namespace = "...")
    @XmlElement(name = "item", namespace = "...")
    public List<Item> getItems() {
      return _items;
    }

    public void setItems(List<Item> items) {
      _items= items;
    }

    @XmlType(name = "Item", namespace = "...")
    public static class Item {

        private Long _id;

        @XmlAttribute(name = "id", namespace = "...")
        public Long getId() {
          return _id;
        }

        public void setId(Long id) {
          _id = id;
        }
    }
}

After unmarshalling, I have request.getItems (). iterator (). next (). getId () == null while it should be 1. If I use nested elements instead of attributes, everything works fine. How can this be fixed? I do not want to write an XmlAdapters batch for all primitive Java types.

+3
source share
1 answer

Attributes in XML by default do not match the namespace of their parent element. So for

<item id="3" xmlns="foo"/>

item foo, id .

, namespace getId():

@XmlAttribute(name = "id")
public Long getId() {
   return _id;
}
+2

Source: https://habr.com/ru/post/1766240/


All Articles