views:

26

answers:

1

I have a problem using Jaxb2Marshaller for unmarshalling XML attributes (of primitive types). Here is the sample:

<?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 is:

@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 just fine. How it could be fixed? I dont'n want to write a batch of XmlAdapters for all primitive Java types.

+2  A: 

Attributes in XML are by default not qualified with the namespace of their parent element. So for

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

The item element has the namespace foo, but the id attribute does not.

To fix your problem, you should just need to remove the namespace declaration from the getId() method:

@XmlAttribute(name = "id")
public Long getId() {
   return _id;
}
skaffman
Thank you. It has solved the problem.
Dair T'arg