我正在尝试将集合(MAP)添加为Node的属性。 我在此查询Xstream Implicit Map As Attributes to Root Element中尝试了代码,但现在可以解决该问题,下面是我尝试过的代码。
@XStreamAlias("TAG")
public class Tag {
private Map<String, String> attributes;
public void addAttribute(String name, String value) {
if (this.attributes == null)
this.attributes = new HashMap<String, String>();
this.attributes.put(name, value);
}
}
public static void main(String[] args) {
XStream xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
Tag tag = new Tag();
tag.addAttribute("KEY1", "VALUE1");
tag.addAttribute("KEY2", "VALUE2");
tag.addAttribute("KEY3", "VALUE3");
System.out.println(xStream.toXML(tag));
}
实际输出如下:
<TAG>
<attributes>
<entry>
<string>KEY2</string>
<string>VALUE2</string>
</entry>
<entry>
<string>KEY1</string>
<string>VALUE1</string>
</entry>
<entry>
<string>KEY3</string>
<string>VALUE3</string>
</entry>
</attributes>
</TAG>
预期输出必须如下
<TAG KEY1=VALUE1 KEY2=VALUE2 KEY3=VALUE3>
</TAG>