Question

I'm trying to unmarshal an xml to an object using moxy.Below is the sample of the xml.

<root>
    <name>
        <firstname>value</firstname>
    </name> 
    <address>value of address</address>
</root>

And below is the class I'm trying to map.

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)

public class Response {
  @XmlPath("name/firstname/text()")
  String name;
  Address address;
}

class Address {
  String addressline;
}

Now how do I get the values of the address tag in XML and bind it to the addressline variable of class Address.

Was it helpful?

Solution

You need to use the @XmlValue annotation on the addressline property.

@XmlAccessorType(XmlAccessType.FIELD)
class Address {
    @XmlValue
    String addressline;
}

OTHER TIPS

this is an answer for a similar (but not exactly the same) question that was linked here:

The solution for our issue relates to this question as well. For the issue above, the short answer (as noted there) is to use @XmlValue attribute with the getMessageText(), not @XmlElement. I had already use 'XmlValue', and it still didn't work, so I reverted to XmlElement.

XmlValue wasn't the whole solution in that case. We also found that we need:

  • @XmlAccessorType( XmlAccessType.NONE )

Apparently because of other stuff in the class. Evidentially JABX tries to match every get/set property with XML and apparently it got confused and can't or won't process my XmlValue if there are non-XML POJO properties (I deduce).

  @XmlAccessorType( XmlAccessType.NONE )
  @XmlRootElement(name = "announcement")
  public class Announcement
  {
      ... 

      @XmlValue
      public  String getMessageText(){
          return this.messageText;
      }
  }

Lesson learned. If your JAXB doesn't do what you think it ought to do, I have confused it. Thanks for the help, knowing what is needed to do, let us find what else we needed too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top