-1

I have a class which looks like this

@XmlRootElement(name="root")
public class MyClass {

@XmlElementWrapper(name="list")
@XmlElement(name="item")
private List<String> myList = new ArrayList<String>();

// getters, setters
}

I want to add an attribute a to list element to reach following XML

<root>
  <list a="1">
    <item>a</item>
    <item>b</item>
    ...
  </list>
</root>

1 Answers1

0

You could create another class for this list as following:-

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name="list")
public class RootList {

    private String a;
    private List<String> someList;

    @XmlAttribute(name="a")
    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    @XmlElement(name="item")
    public List<String> getSomeList() {
        return someList;
    }

    public void setSomeList(List<String> someList) {
        this.someList = someList;
    } 

    public RootList(String numValue,List<String> someListValue) {
        this();
        this.a = numValue;
        this.someList = someListValue;  
    }

    public RootList() {
        // TODO Auto-generated constructor stub
    }
}

To run the above code using JAXB, use the following:

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.*;

public class Test {

        public static void main(String[] args) throws Exception {
            List<String> arg = new ArrayList<String>();
            arg.add("a");
            arg.add("b");
            RootList root = new RootList("1", arg);

            JAXBContext jc = JAXBContext.newInstance(RootList.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.marshal(root, System.out);
        }
}

It will generate the following XML as the output:

<list a="1">
    <item>a</item>
    <item>b</item>
</list>
Jaspreet Jolly
  • 1,235
  • 11
  • 26
  • thank you for ur help very appriciate!! its possible if want keep the root elements and add value to the XMlElementWrapper like this ↓ ** a b ** – teachMepls Aug 26 '19 at 07:43