Alex Dean
Alex Dean

Reputation: 16125

How do I un/marshall attributed elements in JAXB?

It seems like this should be fairly obvious, but I can't find anything on how to simply (un)marshall XML elements which also have attributes using JAXB.

In other words, I understand how to use JAXB annotations to work with:

<element>foo</element>

And I understand how to use JAXB with:

<element attribute1="bar" attribute2="foo" />

But I can't figure out how to approach something like:

<id_address href="/addresses/18">18></id_address_delivery>
<id_cart href="/carts/111">111</id_cart>
<id_currency href="/currencies/13">13></id_currency>

It feels like I should be able to do something like this (I'm using JAXB from Scala):

@XmlElement
@BeanProperty
var idAddress: XLink = _

@XmlElement
@BeanProperty
var idCart: XLink = _

@XmlElement
@BeanProperty
var idCurrency: XLink = _

And then define XLink as:

@XmlAccessorType(XmlAccessType.FIELD)
class XLink {

  @XmlAttribute
  @BeanProperty
  var href: String = _

  @Xml???
  @BeanProperty // ID is the container
  var id: Long = _
}

But obviously this doesn't work, because id shouldn't be a sub-element - it's simply the value of the parent node.

This is such a common use case: what am I missing? For completeness, I'm using JAXB (MOXy) from Scala.

Upvotes: 2

Views: 265

Answers (1)

earldouglas
earldouglas

Reputation: 13473

I think you want @XmlValue.

See here for more info.

Upvotes: 1

Related Questions