[英]XStream custom converter that can generate flat XML structure from List?
I'm using XStream and have a class with a field like the following: 我正在使用XStream,并且有一个类如下的字段:
private Map<String, String> data;
I want to generate XML output like this: 我想生成这样的XML输出:
<key1>test data</key1>
<key2>test data</key2>
<key3>test data</key3>
So I want the map key to be the element. 所以我希望map键成为元素。 The mapvalue to be the XML value and I don't want the XML wrapped in an element such as
<data></data>
. mapvalue是XML值,我不希望XML包含在诸如
<data></data>
类的元素中。 Can anyone point to sample code that does this, or something similar? 任何人都可以指向执行此操作的示例代码或类似的东西吗?
UPDATE UPDATE
This just a snippet, there is a root element. 这只是一个片段,有一个根元素。
UPDATE 2 更新2
The custom converter code I posted below almost works. 我发布的自定义转换器代码几乎可以使用。 I get a flat structure, but I need to remove the outer element.
我得到一个扁平的结构,但我需要删除外部元素。 Any idea on that?
有什么想法吗?
//this is the result need to remove <data>
<data>
<key1>test data</key1>
<key2>test data</key2>
<key3>test data</key3>
</data>
This is the code 这是代码
public class MapToFlatConverter implements Converter{
public MapToFlatConverter() {
}
@Override
public boolean canConvert(Class type) {
return Map.class.isAssignableFrom(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Map<String, String> map = (Map<String, String>) source;
for (Map.Entry<String, String> entry : map.entrySet()) {
writer.startNode(entry.getKey());
writer.setValue(entry.getValue().toString());
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
//not needed at this time
return null;
}
} }
I was able to get this working. 我能够让这个工作。 The following SO post is what I ultimately did: custom converter in XStream .
以下SO帖子是我最终做的: XStream中的自定义转换器 。 I needed to extend from the ReflectionConverter:
我需要从ReflectionConverter扩展:
This next post helped also, though when I tried this approach the context.convertAnother() method did not seem to work. 下一篇文章也有所帮助,但是当我尝试这种方法时,context.convertAnother()方法似乎不起作用。 So I switched to the method in the 1st post.
所以我在第一篇文章中切换到了方法。
Xstream Implicit Map As Attributes to Root Element Xstream隐式映射作为根元素的属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.