Aliasing contents of a Set using XStream

扶醉桌前 提交于 2019-12-11 12:48:32

问题


I have a problem with aliasing in XStream.

I've got a set of String items that I would like to serialize to XML like this:

<types>
  <type>abc</type>
  <type>def</type>
</types>

However, I can't seem to find a good way to solve this. I've tried a list of strings, but then I end up with

<types>
  <string>abc</string>
  <string>def</string>
</types>

I've also tried putting the String in a simple class, but then I get

<types>
  <type>
    <aType>abc</aType>
  </type>
</types>

where <type> is the alias of the custom class, and aType is the attribute in the class, i.e I get one level too much using this approach. How would I go about eliminating the extra level or simply substituting the <string> with a custom tag name?


回答1:


You will need to alias both the List and the items in the list.

List<String> types = new ArrayList<String>();
types.add("abc");
types.add("def");

XStream xstream = new XStream();
xstream.alias("types", List.class);
xstream.alias("type", String.class);
System.out.println(xstream.toXML(types));

Will result in

<types>
  <type>abc</type>
  <type>def</type>
</types>


来源:https://stackoverflow.com/questions/8066917/aliasing-contents-of-a-set-using-xstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!