问题
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.
回答1:
You need to use the @XmlValue
annotation on the addressline
property.
@XmlAccessorType(XmlAccessType.FIELD)
class Address {
@XmlValue
String addressline;
}
回答2:
this is an answer for a similar (but not exactly the same) question that was linked here:
- How can I encourage JAXB to read XmlElement content string?
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.
来源:https://stackoverflow.com/questions/24053083/how-to-bind-a-xml-element-into-an-object-member-variable