【问题标题】:JAXB Unmarshall same elements with different attributes (lang)JAXB Unmarshal 具有不同属性的相同元素(语言)
【发布时间】:2013-07-17 20:36:00
【问题描述】:

我有一个 REST xml 提要,其中包含以下语言区分用法

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

lang 属性与多个不同的元素一起出现,除了名称。 有没有办法让我根据所选语言仅使用一个元素轻松解组它?或者获得List 或更好的Map

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

编辑:我还没有考虑 MOXy,如果 JAXB 无法单独完成,我可能不得不考虑。

【问题讨论】:

    标签: java xml jaxb unmarshalling


    【解决方案1】:

    注意:我是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);
        }
    
    }
    

    更多信息

    【讨论】:

    • 这很简单,相信我。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多