我有一个XmlElementWrapper注释类,如:
…
- @XmlElementWrapper(name="myList")
- @XmlElements({
- @XmlElement(name="myElement") }
- )
- private List<SomeType> someList = new LinkedList();
- <myList>
- <myElement> </myElement>
- <myElement> </myElement>
- <myElement> </myElement>
- </myList>
到现在为止还挺好。
- <myList number="2">
- <myElement> </myElement>
- <myElement> </myElement>
- <myElement> </myElement>
- </myList>
有没有一个’聪明的方式来实现这个没有创建一个新的类包含代表列表?
我为你的问题找到了一个更好的解决方案。
要使Xml Java对象使用以下代码:
- import java.util.*;
- import javax.xml.bind.annotation.*;
- @XmlRootElement(name="myList")
- public class Root {
- private String number;
- private List<String> someList;
- @XmlAttribute(name="number")
- public String getNumber() {
- return number;
- }
- public void setNumber(String number) {
- this.number = number;
- }
- @XmlElement(name="myElement")
- public List<String> getSomeList() {
- return someList;
- }
- public void setSomeList(List<String> someList) {
- this.someList = someList;
- }
- public Root(String numValue,List<String> someListValue) {
- this();
- this.number = numValue;
- this.someList = someListValue;
- }
- /**
- *
- */
- public Root() {
- // TODO Auto-generated constructor stub
- }
}
要使用JAXB运行上述代码,请使用以下命令:
- import java.util.ArrayList;
- import java.util.List;
- import javax.xml.bind.*;
- public class Demo {
- public static void main(String[] args) throws Exception {
- List<String> arg = new ArrayList<String>();
- arg.add("FOO");
- arg.add("BAR");
- Root root = new Root("123",arg);
- JAXBContext jc = JAXBContext.newInstance(Root.class);
- Marshaller marshaller = jc.createMarshaller();
- marshaller.marshal(root,System.out);
- }
- }
这将产生以下XML作为输出:
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <myList number="123">
- <myElement>FOO</myElement>
- <myElement>BAR</myElement>
- </myList>
我觉得这对你更有帮助
谢谢..