2013-07-18 110 views
3

JAXB解组相同的元件我有语言分化的以下使用一个REST XML饲料具有不同属性(朗)

<name xml:lang="cs">Letní 2001/2002</name> 
<name xml:lang="en">Summer 2001/2002</name> 

lang属性与多个不同的元素,比其他名称发生。 只有一种基于所选语言的元素,我可以轻松解开它吗?或者获得List或更好的Map他们两个?

我知道我可以通过为每个元素创建一个不同的类来做到这一点,但我不想仅仅因为每种资源的语言选择就有五十个类。

编辑:我还没有考虑过MOXY,如果JAXB无法做到这一点,我可能不得不这样做。

回答

0

备注:我是EclipseLink JAXB (MOXy)的领导者和JAXB (JSR-222)专家组的成员。

莫西允许你使用它的@XmlPath扩展映射到基于XML属性值的元素:

Java模型(美孚)

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); 
    } 

} 

更多信息

+1

这是很简单的,认为我信服。谢谢 – Meltea

相关问题