App下載
首頁javajaxbJava HTML/XML - 如何使用@XmlElement注釋列表

Java HTML/XML - 如何使用@XmlElement注釋列表

我們想知道如何使用@XmlElement注釋列表。
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Content.class);

    List<String> strings = new ArrayList<String>(2);
    strings.add("foo");
    strings.add("bar");

    Content content = new Content();
    content.setKeywords(strings);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(content, System.out);
  }

  @XmlRootElement
  public static class Content {

    private List<String> keywords;

    public Content() {
    }

    @XmlElementWrapper
    @XmlElement(name = "keyword")
    public List<String> getKeywords() {
      return keywords;
    }

    public void setKeywords(List<String> keywords) {
      this.keywords = keywords;
    }

  }
}