首页 > 解决方案 > 如何使用 jaxb 将包含相同元素的不同类型的元素映射到单个 java 类 objetc

问题描述

我的问题是客户端 sendind xml 请求包含具有相同名称的不同类型的元素,我需要转换为 java 对象。我在下面添加请求。第一个请求是:-

 <root>
  <params>
    <game>1</game>
  </params>
</root>

第二个是:-

<root>
    <params>
         <game>
            <id>1</id>
            <name>Lucky 7</name>
            <translation>Lucky 7</translation>
        </game>
    </params>
</root>

我已经查看了stakeoverflow,但我没有得到解决方案。希望有人可以帮助添加到单个java类中,而不是使用多个java类。

标签: javaxmljaxb

解决方案


父元素同时具有子元素和文本值,使用@XmlMixed注解通过 JAXB 解组提取父元素的文本值

尝试以下示例,

游戏.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <game>1</game>  <!-- text value -->
    <game>
        <id>1</id>  <!-- child element -->
        <name>Lucky 7</name>
        <translation>Lucky 7</translation>
    </game>
</root>

根.java

@XmlRootElement
public class Root {

    private List<Game> listGame;

    @XmlElement(name="game")
    public List<Game> getListGame() {
        return listGame;
    }

    public void setListGame(List<Game> listGame) {
        this.listGame = listGame;
    }
}

游戏.java

@XmlRootElement
public class Game {

    private List<String> textValue;
    private String id;
    private String name;
    private String translation;

    @XmlMixed
    public List<String> getTextValue() {
        return textValue;
    }
    public void setTextValue(List<String> textValue) {
        this.textValue = textValue;
    }
    @XmlElement
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlElement
    public String getTranslation() {
        return translation;
    }
    public void setTranslation(String translation) {
        this.translation = translation;
    }
}

使用 JAXB 解组,

File file = new File("game.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root) jaxbUnmarshaller.unmarshal(file);

for (int i = 0; i < root.getListGame().size(); i++) {
    System.out.println("Game Object "+(i+1));
    if(root.getListGame().get(i).getTextValue().size()>1){
        System.out.println("ID :"+root.getListGame().get(i).getId());
        System.out.println("Name :"+root.getListGame().get(i).getName());
        System.out.println("Translation :"+root.getListGame().get(i).getTranslation());
    }else{
        System.out.println("Value :"+root.getListGame().get(i).getTextValue().get(0));
    }
    System.out.println("------------------------------------");
}

输出,

Game Object 1
Text Value :1
------------------------------------
Game Object 2
ID :1
Name :Lucky 7
Translation :Lucky 7
------------------------------------

欲了解更多信息,https://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlMixed.html

谢谢,


推荐阅读