5

I have something like

@XmlElementWrapper(name="Mylist")
List<Items> myItems = new ArrayList<Items>()

and that comes out like

<Mylist>
   <myItems>item 1</myItems>
   <myItems>item 2</myItems>
   <myItems>item 3</myItems>
</Mylist>

Is it possible to make this come out more like

<Mylist>
   <myItems>item 1, item 2, item 3</myItems>
</Mylist>

Since the data I am after is all just textual anyway?

3 Answers 3

6

You can use @XmlList to make it a space separated value.

For a comma separated list you will need to use an XmlAdapter. For more information on XmlAdapter see:

Sign up to request clarification or add additional context in comments.

2 Comments

Are you saying in the new adapter class then I would simply cat all the items in the list together, and use @XmlValue on the newly created string?
Yes, then going the other direction you could tokenize the String on the ',' character.
2

Here's an XmlAdapter to handle comma separated lists:

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CommaSeparatedListAdapter extends XmlAdapter<String, List<String>> {

    @Override
    public List<String> unmarshal(final String string) {
        final List<String> strings = new ArrayList<String>();

        for (final String s : string.split(",")) {
            final String trimmed = s.trim();

            if (trimmed.length() > 0) {
                strings.add(trimmed);
            }
        }

        return strings;
    }

    @Override
    public String marshal(final List<String> strings) {
        final StringBuilder sb = new StringBuilder();

        for (final String string : strings) {
            if (sb.length() > 0) {
                sb.append(", ");
            }

            sb.append(string);
        }

        return sb.toString();
    }
}

You would use it like this:

@XmlElementWrapper(name="Mylist")
@XmlJavaTypeAdapter(CommaSeparatedListAdapter.class)
List<Items> myItems = new ArrayList<Items>()

Comments

0

you can accomplish that by making the field transient @XmlTransient and creating a method for calculating a String with a comma-separated.

@XmlTransient
List<Items> myItems = new ArrayList<Items>()

@XmlElement(name = "myItems")
public String getItemsAsCommasSeparated() {
    return String.join(", ", myItems);
}

About the wrapping <Mylist> if it is really necessary you will have to wrap the list into a another object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.