2013-07-18 104 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

相關問題