简体   繁体   English

如何使用不同标签解组XML

[英]How to unmarshalling xml with different tags

I've got this xml code: 我有以下xml代码:

<?xml version="1.0" encoding="UTF-8"?>
  <root>
      <beer>some beer</beer>
      <beer>some another beer</beer>
      <food>some food</food>
      <food>some another food</food>
  </root>`enter code here`

To unmarshalling this xml with JAXB I'm using this source: 要使用JAXB解组此xml,请使用以下源:

@XmlElement(name="beer")
public void setKey(Set<String> key)
{
    this.key = key;
}

When I unmarshalling xml for Set I've receive the result: "some beer" and "some another beer", because the anotation and the tag name. 当我为Set解组xml时,我收到了结果:“一些啤酒”和“一些其他啤酒”,因为注释和标签名称。 So how can I parse all childs from the "root" tag. 因此,我该如何解析“ root”标记中的所有子项。 ie result in Set have to be: some beer, some another beer, some food, some another food. 即Set的结果必须是:一些啤酒,一些其他啤酒,一些食物,一些其他食物。

Thanks previously for the time spend for my issue. 以前感谢您花费我的时间。

Do you really need JAXB for this? 您真的需要JAXB吗? If so, maybe something like this will help: 如果是这样,也许这样的事情会有所帮助:

import java.util.ArrayList;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "beer",
    "food"
})
@XmlRootElement(name = "root")
public class Root {

    @XmlElement(required = true)
    protected List<Beer> beer;
    @XmlElement(required = true)
    protected List<Food> food;

public List<Beer> getBeer() {
        if (beer == null) {
            beer = new ArrayList<Beer>();
        }
        return this.beer;
    }

public List<Food> getFood() {
        if (food == null) {
            food = new ArrayList<Food>();
        }
        return this.food;
    }

}

Also you need to create Food and Beer classes with getters and setters. 另外,您还需要使用吸气剂和吸气剂创建食品和啤酒类。 For lists there is no need to create setters, because you can use add() after getter. 对于列表,不需要创建setter,因为可以在getter之后使用add()。 But I recommend to use DOM for this task. 但我建议将DOM用于此任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM