我有一个 REST xml 提要,具有以下语言区分用法
<name xml:lang="cs">Letní 2001/2002</name>
<name xml:lang="en">Summer 2001/2002</name>
除了名称之外,lang 属性出现在多个不同的元素中。
有没有一种方法可以让我根据所选语言仅使用一个元素轻松解码它?或者得到一个 List
或更好的 Map
两者?
我知道我可以通过为每个元素创建一个不同的类来做到这一点,但我不想仅仅因为语言选择就为每个资源创建五十个类。
编辑:我还没有考虑过 MOXy,如果仅靠 JAXB 无法做到这一点,我可能不得不考虑。
最佳答案
注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。
MOXy 允许您使用其 @XmlPath
扩展名映射到基于 XML 属性值的元素:
Java 模型(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;
}
演示
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);
}
}
了解更多信息
关于java - JAXB 解码具有不同属性的相同元素 (lang),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731167/