I have a REST xml feed with the following usage of language differentiation
<name xml:lang="cs">Letní 2001/2002</name>
<name xml:lang="en">Summer 2001/2002</name>
The lang attribute occurs with multiple different elements, other than name. Is there a way for me to unmarshall it easily with only one of the elements based on the selected language? Or get a List
or better a Map
of both of them?
I know I could possibly do it by creating a different class for each of the elements, but I don't want to have fifty classes just because the language choice, for each resource.
edit: I have not yet considered MOXy, I will probably have to if this can't be done by JAXB alone.
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
MOXy allows you to map to an element based on the value of an XML attribute using its @XmlPath
extension:
Java Model (Foo)
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
@XmlPath("name[@xml:lang='cs']/text()")
private String csName;
@XmlPath("name[@xml:lang='en']/text()")
private String enName;
}
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum17731167/input.xml");
Foo foo = (Foo) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
For More Information
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.