我正在尝试反序列化这样的 XML 文档:
<rootelem>
<elementType1 arg1="..." />
<elementType1 arg1="..." />
<elementType1 arg1="..." />
<elementType2 argA="..." argB="..." />
<elementType2 argA="..." argB="..." />
<elementType2 argA="..." argB="..." />
</rootelem>
默认情况下XStream只能解析这样的形式:
<rootelem>
<list1>
<elementType1 arg1="..." />
<elementType1 arg1="..." />
<elementType1 arg1="..." />
</list1>
<list2>
<elementType2 argA="..." argB="..." />
<elementType2 argA="..." argB="..." />
<elementType2 argA="..." argB="..." />
</list>
</rootelem>
这是因为 XStream 使用下一种格式进行集合:
<collection>
<elem .... />
<elem .... />
<elem .... />
</collection>
和框架标签是强制性的。集合只能包含单一类型的节点。那么如何解析这样的XML文档呢?现在我已经为此编写了自己的转换器,但我想知道还有其他方法吗?
最佳答案
我认为隐式集合是适合您的解决方案。
http://x-stream.github.io/alias-tutorial.html#implicit
这里是示例代码:
package com.thoughtworks.xstream;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
teamBlog.add(new Entry("first","My first blog entry."));
teamBlog.add(new Entry("tutorial",
"Today we have developed a nice alias tutorial. Tell your friends! NOW!"));
XStream xstream = new XStream();
xstream.alias("blog", Blog.class);
xstream.alias("entry", Entry.class);
xstream.addImplicitCollection(Blog.class, "entries");
System.out.println(xstream.toXML(teamBlog));
}
}
结果:
<blog>
<author>
<name>Guilherme Silveira</name>
</author>
<entry>
<title>first</title>
<description>My first blog entry.</description>
</entry>
<entry>
<title>tutorial</title>
<description>
Today we have developed a nice alias tutorial. Tell your friends! NOW!
</description>
</entry>
</blog>
关于java - XStream 单个集合中的多种节点类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096603/