问题
Image I have an element like this <someElement a="" b="" number="1" scale="meters"><child/></someElement>
scale and number always appear together but they are not defined in one exclusive element.
When unmarshalling the someElement
element to a SomeElement
java instance I want a single member in the SomeElement
class to represent number
and scale
.
At the moment both number and scale are attributes and then the afterUnmarshall()
method is used for calculating one number.
Is there a way to do this without having the two member fields size and scale? Maybe with a XmlAdapter
? How would I use this in this case?
回答1:
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
MOXy offers the @XmlTransformation
extension that allows you to represent a Java field/property as several XML nodes.
For More Information
- http://blog.bdoughan.com/2010/08/xmltransformation-going-beyond.html
UPDATE
Alternatively you could use an XmlAdapter
for this use case. The adapter will we responsible for converting the single type representing number and scale (represented as FOO below) to a type with separate properties for number and scale. You will still need to use the MOXy implementation to leverage the @XmlPath
extension:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SomeElement {
@XmlAttribute
private String a;
@XmlAttribute
private String b;
@XmlJavaTypeAdapter(NumberAndScaleAdapter.class)
@XmlPath(".")
private FOO numberAndScale;
private Child child;
}
For More Information
- http://blog.bdoughan.com/search/label/XmlAdapter
- http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
回答2:
The answers for this question seem to correspond with what you're trying to do. Or at least some reverse of it. So you can either create a custom type that un/marshals using an XmlAdapter, or you can be mischievous with your getter/setter logic.
来源:https://stackoverflow.com/questions/7936104/jaxb-convert-multiple-attributes-to-one-type-while-unmarshalling